Anonymous functionThe function of use is to inherit variables from the parent scope.
The following example is the most common usage. If use is not used, the variable $msg will not be found in the function.
Array ( [0] => 1 [1] => 2 [2] => 3 )
The behavior of inheriting variablesIs it generated when the function is defined or Generated when a function is called? Let’s adjust the order of the code in the above example and place $msg after the function definition.
PHP Notice: Undefined variable: msg in /search/ballqiu/c.php on line 4
msg is defined, so $msg is the un
defined variablewhen the function is run.
Run output
Array ( [0] => 2 [1] => 2 [2] => 3 ) Array ( [0] => 2 [1] => 2 [2] => 3 )
So in any case, if you want to change the value of an external variable through an anonymous function, you must pass the value to use by reference? Look at the following example:
Run output
ArrayObject Object ( [storage:ArrayObject:private] => Array ( [0] => 2 [1] => 2 [2] => 3 ) ) ArrayObject Object ( [storage:ArrayObject:private] => Array ( [0] => 2 [1] => 2 [2] => 3 ) )
It can be seen that if you pass a variable of type
object class, even if you do not display the use of reference passing, the variable value in the anonymous function Changes also affect external related variables.
But, the problem came again. When passing an object variable to use, is there any difference between using a reference and not using a reference? Let’s look at the example
We use reference passing instead
$func = function()use(&$msg){ echo $msg[0],"\n"; }; 运行输出1
It can be seen that when using reference passing, even if the variable lags behind the function definition, the corresponding external variable can still be found inside the function and will not appear The variable is undefined. There is still a difference between the two.
_num++, "\n"; }; return $func; } public function get(){ echo $this->_num,"\n"; } }$obj = new C();$func = $obj->mkFunc();$func();$obj->get();?> 运行结果01
, no You can find it directly if you need to use use.Still the above example, what will be the effect if you must use use?
Change mkFunc topublic function mkFunc(){ //唯一改动是此处加了use $func = function()use($this){ echo $this->_num++, "\n"; }; return $func; } 运行输出 PHP Fatal error: Cannot use $this as lexical variable
public function mkFunc(){ $self = $this; $func = function()use($self){ echo $this->_num++, "\n"; }; return $func; } 运行结果01
It can be seen that the effect is the same whether use is used.
The above is the detailed content of What is the use of use in php anonymous function. For more information, please follow other related articles on the PHP Chinese website!