Reputation: 17625
So far I only see closure in javascript:
var name=...;
$(..).onclick(function() {
//here I can reference to name
});
Does this feature exist in c/c++/java/PHP
?
If exists,one hello world example available?
Upvotes: 0
Views: 496
Reputation: 3635
As for PHP, you can enable access to a specific variable inside a closure method like this:
$xVar = "var";
$closure = function() use ($xVar) {
echo $xVar;
}
$closure();
And it's also possible to alter this variable inside the closure:
$xVar = "var";
$closure = function($newVar) use (&$xVar) {
$xVar = $newVar;
}
$closure("new var content");
Upvotes: 2
Reputation: 718836
At one point, closures (Project Lambda) were going to be part of Java 7, but they are currently listed as "Deferred to Java 8 or later".
Upvotes: 1
Reputation: 92056
For C, they are available as a non-standard extension called blocks.
Upvotes: 0
Reputation: 131799
C no, as functions aren't first-class objects.
C++ not yet, but it does with the upcoming standard (commonly referred to as C++0x), with so called lambda expressions:
std::string name;
auto mylambda = [&](){ std::cout << name; };
// ^ automatically reference all objects in the enclosing scope.
Upvotes: 1
Reputation: 78463
PHP has those too, since 5.3. They're not as flexible (in that you can't use $this
), but still very useful.
Lisp and its dialects also have closures.
Upvotes: 0
Reputation: 678
http://en.wikipedia.org/wiki/Closure_%28computer_science%29#PHP
For PHP
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
?>
Upvotes: 0