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)

2 answers 2

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 
  • so what's the difference between the usual arguments and the design use ? - MaximPro
  • one
    @MaximPro, Arguments to an anonymous function are then installed by someone ( array_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 . - user207618
  • seemingly understandable and incomprehensible - MaximPro
  • @MaximPro, what exactly is incomprehensible to you? - user207618
  • How can we set arguments to an anonymous function if we haven't put it in a variable? I array_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 pm

In 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!