简体   繁体   中英

PHP variables in anonymous functions

I was playing around with anonymous functions in PHP and realized that they don't seem to reach variables outside of them. Is there any way to get around this problem?

Example:

$variable = "nothing";

functionName($someArgument, function() {
  $variable = "something";
});

echo $variable;  //output: "nothing"

This will output "nothing". Is there any way that the anonymous function can access the $variable ?

Yes, use a closure :

functionName($someArgument, function() use(&$variable) {
  $variable = "something";
});

Note that in order for you to be able to modify $variable and retrieve the modified value outside of the scope of the anonymous function, it must be referenced in the closure using & .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM