compile-fan
compile-fan

Reputation: 17625

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

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

Answers (7)

Rick Pastoor
Rick Pastoor

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

Stephen C
Stephen C

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

missingfaktor
missingfaktor

Reputation: 92056

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

Upvotes: 0

Node
Node

Reputation: 3509

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

Upvotes: 1

Xeo
Xeo

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

Denis de Bernardy
Denis de Bernardy

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

Johannes Reiners
Johannes Reiners

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

Related Questions