Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

lambda

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

like image 486
Baptiste Costa Avatar asked Aug 06 '15 08:08

Baptiste Costa


1 Answers

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"
like image 69
Sylwester Avatar answered Nov 20 '22 05:11

Sylwester