PHP equivalent to [&, epsilon] C ++ "Capturing" variables in lambda?

Is there a way to pass any variable that is currently in scope with a link to a lambda function without listing all of them in the use(...) statement?

Something like

 $foo = 12; $bar = 'hello'; $run = function() use (&) { $foo = 13; $bar = 'bye'; } // execute $run function 

The result of $foo is 13 and $bar is equal to 'bye' .

+7
lambda php
source share
2 answers

TL; DR The short answer is no. You need to specify variables

You do not need closure variables for this. You cannot even use use with named functions, since it will not have a nested lexical scope. Use the global to make variables dynamic. You must specify all special variables.

 $foo = 12; $bar = 'hello'; function run() { global $foo,$bar; $foo = 13; $bar = 'bye'; } run(); print "$foo, $bar\n"; // prints "13, bye" 

For lexical anonymous functions, you need to name all the variables with use and use & to get the link:

 $foo = 12; $bar = 'hello'; $run = function () use (&$foo,&$bar) { $foo = 13; $bar = 'bye'; }; call_user_func($run); print "$foo, $bar\n"; // prints "13, bye" 
+1
source share

You can use get_defined_vars() along with extract() :

 $foo = 12; $bar = 'hello'; $vars = get_defined_vars(); foreach (array_keys($vars) as $var) { $vars[$var] = &$$var; // keep refs of all variables from current scope } $run = function() use($vars) { extract($vars, EXTR_REFS); $foo = 13; $bar = 'bye'; }; // execute $run function $run(); print $foo; // prints 13 print $bar; // prints bye 
0
source share

All Articles