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');
};
Not in PHP 5.x; unless you count it when your method takes a callback as an argument. eg:
The
use
keyword indicates which variables from the current lexical scope should be imported into the closure. You can even pass them by reference and change the variable being passed, eg:Closures defined inside a class have full access to all its properties and methods, including private ones with no need to import
$this
through the keyworduse
in PHP 5.4:Note that for some strange reason support for
$this
in closures was removed in PHP 5.3. In this version, you can work around this restriction using something like:But this gives you access to public members only, attempting to access private members will still give you an error.
Also note that attempting to import
$this
(viause
), regardless of the PHP version, will result in a fatal errorCannot use $this as lexical variable
.PHP 7 added the ability to do this.
This code:
works as one would expect in PHP 7. (It still doesn't work in any PHP 5.x. release)
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 anunexpected '('
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.