Php variables in anonymous functions

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

Example:

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

It will display: "nothing." Is there a way for an anonymous function to access the $ variable?

+102
function variables php global-variables anonymous
Jul 10 '12 at 19:30
source share
1 answer

Yes, use closure :

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

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

+241
Jul 10 '12 at 19:31
source share



All Articles