tags:

views:

55

answers:

2

A php closure or anonymous function is used to create function without specifying its name.

Is it possible to call them without assigning to identifier as we do in JavaScript ? e.g.

(function(){
    echo('anonymous function');
})();

What is the correct use of use construct while defining anonymous function and what is the status of anonymous function in public method with accessibility to private properties?

$anon_func = 
function($my_param) use($this->object_property){ //use of $this is erroneous here
    echo('anonymous function');
};
+1  A: 

Doesn't look like it, as they still have to be declared with the function() {} notation, and on my 5.3.2 install, trying your sample notion returns an unexpected '(' syntax error. The doc page on closures doesn't mention it either.

Maybe it'll become possible once they patch up the parser to allow somefunction()[2] array dereferencing.

Marc B
+3  A: 

Is it possible to call them without assigning to identifier as we do in JavaScript ? e.g.

No, unless you count it when your method takes a callback as an argument. eg:

$square = array_map(function ($v) { return $v*$v; }, $array);

What is the correct use of use construct while defining anonymous function

The use keyword indicate which variables from the current lexical scope should be exported to the closure. You can even pass them by reference and change the variable being passed, eg:

$total = 0;
array_walk($array, function ($v) use (&$total) { $total += $v; });
// $total is now the sum of elements in $array

what is the status of anonymous function in public method with accessibility to private properties?

Closures defined inside a class had full access to all its properties and methods, including private ones with no need to import $this through the keyworduse. But apparently support for $this has been removed from closures (you can't import it any more).

See here: http://wiki.php.net/rfc/closures/removal-of-this

NullUserException
+1 It is not possible to self-invoke anonymous functions like `(function() {})();` in PHP though, probably for the same reasons array dereferencing isn't yet doable either as Marc B notes.
BoltClock