I stumbled upon such an unusual construction; I have never seen it anywhere before:
$variable = function($any) use ($alternate_var, &$yet) { /// Any code };
How this construct works, it is particularly interesting to use ($alternate_var, &$yet)
I stumbled upon such an unusual construction; I have never seen it anywhere before:
$variable = function($any) use ($alternate_var, &$yet) { /// Any code };
How this construct works, it is particularly interesting to use ($alternate_var, &$yet)
Read .callback
function
That is, when a function is needed, but laziness / other_reason to create a separate function that you pass as a parameter once.
By decision from Above, they do not have access to the parent scope, so use is used as a method of passing variables into the local context callback
function.
$a = 1; $b = [5]; array_map(function($q){ print $a; }, $b); // Undefined variable: a $a = 1; $b = [5]; array_map(function($q) use ($a){ print $a; }, $b); // 1
It is important :
The use
construct passes a value , not a link That is, a change in the passed variable will not affect the parent variable. If necessary, use &
:
$a = 1; $b = [5]; array_map(function($q) use (&$a){ print $a; $a = 2; }, $b); print $a; // 12
use
? - MaximProarray_map
, for example, will pass the array values ​​to the arguments), and you will not pass the access to the parent scope. Here also use use
. - user207618array_map(function($q) use (&$a){ print $a; $a = 2; }, $b);
this array_map(function($q) use (&$a){ print $a; $a = 2; }, $b);
- MaximPro 2:26 pmIn the above example, an anonymous function is used with inheriting a variable from the parent scope. (Read more http://php.net/manual/ru/functions.anonymous.php )
Article on Habré about the use of closures in PHP here .
Example:
$alternate_var = 'world'; $yet = '!'; $variable = function($any) use ($alternate_var, &$yet) { return $any . $alternate_var . $yet; }; echo $variable('Hello '); // Hello world!
Source: https://ru.stackoverflow.com/questions/554392/
All Articles