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
usekeyword 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
$thisthrough the keywordusein PHP 5.4:Note that for some strange reason support for
$thisin 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.