There is an example anonymous function in the document
闭包可以从父作用域中继承变量。 任何此类变量都应该用 use 语言结构传递进去
$message = 'hello';// 没有 "use"$example = function () { var_dump($message);};echo $example();// 继承 $message$example = function () use ($message) { var_dump($message);};echo $example();
useWhat is the mechanism of action here? Don't understand, solve!
Reply content:
There is an example anonymous function in the document
闭包可以从父作用域中继承变量。 任何此类变量都应该用 use 语言结构传递进去
$message = 'hello';// 没有 "use"$example = function () { var_dump($message);};echo $example();// 继承 $message$example = function () use ($message) { var_dump($message);};echo $example();
useWhat is the mechanism of action here? Don't understand, solve!
useThe mechanism here is not just anonymous functions, but a more explicit definition called closures , and closures are generally implemented by anonymous functions.
This is use actually a copy of the global $message to the local function, so very similar to global , but unlike global is:
useTime: When you make changes to a function $message , it does not affect the global one $message , which means that the use use is actually a copy of a variable into a function.
globalWhen: On the contrary, the change in the function $message affects the global one $message .
More specific content, you can see my this blog php anonymous functions and closures
It's the equivalent of global.
function() { global $message; var_dump($message);}
If you look at anonymous functions that are unfamiliar, you might as well look at this code:
$message = 'hello';// 没有 "use"$example = function () { var_dump($message);};echo $example();// 继承 $message$example = function ($message) { global $message; var_dump($message);};echo $example($message);
The result of the output is the same as the anonymous function under the use mechanism, with the effect of "using the parent-scoped variable in the child scope."
There is a need to specifically declare use or global because the scope of variables in PHP's functions is local, unlike JavaScript, which allows layers to be looked up to the outer scope.