einord einord - 2 years ago 115
PHP Question

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?


$variable = "nothing";

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

echo $variable;

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

Answer Source

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 &.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download