Is it possible to call them without
assigning to identifier as we do in
JavaScript ? e.g.
Not in PHP 5.x; 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 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:
$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 have full access to all its properties and methods, including private ones with no need to import $this
through the keyword use
in PHP 5.4:
// this works fine in PHP 5.4
$anon_func =
function($my_param) {
$thing = $my_param + $this->object_property;
echo('anonymous function');
};
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:
// a workaround for PHP 5.3
$temp = $this;
$anon_func =
function($my_param) use ($temp) {
$thing = $my_param + $temp->object_property;
echo('anonymous function');
};
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
(via use
), regardless of the PHP version, will result in a fatal error Cannot use $this as lexical variable
.
Closure
. Just so you know. – Beberg