Is there a way I can pass any variable currently in scope by reference to a lambda function without listing them all in the use(...)
statement?
Something like
$foo = 12;
$bar = 'hello';
$run = function() use (&) {
$foo = 13;
$bar = 'bye';
}
// execute $run function
Resulting in $foo
equal to 13
and $bar
equal to 'bye'
.
TL;DR The short answer is no. You need to name the variables
You don't need closure variables for this. It's not even valid to use use
with named functions since it won't have a nested lexical scope. Use the global
keyword to make the variables "dynamic". You have to name all the variables that are special.
$foo = 12;
$bar = 'hello';
function run() {
global $foo,$bar;
$foo = 13;
$bar = 'bye';
}
run();
print "$foo, $bar\n"; // prints "13, bye"
For a lexical anonymous functions you need to name all variables with the use
keyword and use &
to get it referenced:
$foo = 12;
$bar = 'hello';
$run = function () use (&$foo,&$bar) {
$foo = 13;
$bar = 'bye';
};
call_user_func($run);
print "$foo, $bar\n"; // prints "13, bye"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With