开发者

Does c/c++/java/PHP have closure?

So far I only see closure in javascript:

var name=...;

$(..).o开发者_如何学Pythonnclick(function() {
     //here I can reference to name
});

Does this feature exist in c/c++/java/PHP?

If exists,one hello world example available?


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");


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.


C++11 has closures, as does PHP. Im not sure about Java.


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".


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');
?>


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.


For C, they are available as a non-standard extension called blocks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜