In this document, the anonymous function closure can inherit variables from the parent scope. Any such variables should be passed in {code...} using the use language structure. What is the mechanism of use? I don't know much about it! The document provides an example of an anonymous function.
The closure can inherit variables from the parent scope. Any such variables should be passed in the use language structure.
$ Message = 'hello'; // No "use" $ example = function () {var_dump ($ message) ;}; echo $ example (); // inherit $ message $ example = function () use ($ message) {var_dump ($ message) ;}; echo $ example ();
Hereuse
What is the mechanism of action? I don't know much about it!
Reply content:
The document provides an example of an anonymous function.
The closure can inherit variables from the parent scope. Any such variables should be passed in the use language structure.
$ Message = 'hello'; // No "use" $ example = function () {var_dump ($ message) ;}; echo $ example (); // inherit $ message $ example = function () use ($ message) {var_dump ($ message) ;}; echo $ example ();
Hereuse
What is the mechanism of action? I don't know much about it!
Hereuse
The mechanism is not just an anonymous function, but more clearly definedClosureClosures are generally implemented through anonymous functions.
Hereuse
In fact$message
Copy to a local function, so it is similarglobal
But unlike global:
use
When you are in the function$message
The change will not affect the global one.$message
In other words, useuse
Actually, a copy of the variable is copied to the function.
global
Time: opposite, in the function$message
The Global One will be affected during the change.$message
.
For more details, refer to my blog on PHP anonymous functions and closures.
It's equivalent to global.
function() { global $message; var_dump($message);}
If you are unfamiliar with anonymous functions, you may want to look at the code below:
$ Message = 'hello'; // No "use" $ example = function () {var_dump ($ message) ;}; echo $ example (); // inherit $ message $ example = function ($ message) {global $ message; var_dump ($ message) ;}; echo $ example ($ message );
The output result is the same as the anonymous function under the use mechanism."Get the variables in the parent scope to the sub-scope for use ".
The reason why we need to specifically declare use or global is that the variable scope in PHP functions is partial, unlike JavaScript, which allows a layer-by-layer query to the outer scope.