PHP等同于[&,epsilon] C++"捕获"lambda中的变量?

Bap*_*sta 7 php lambda

有没有办法通过引用lambda函数传递当前在范围内的任何变量而不在use(...)语句中列出它们?

就像是

$foo = 12;
$bar = 'hello';

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

// execute $run function
Run Code Online (Sandbox Code Playgroud)

导致$foo等于13$bar等于'bye'.

Syl*_*ter 1

TL;DR 简短的回答是否定的。您需要命名变量

为此,您不需要闭包变量。它甚至不能use与命名函数一起使用,因为它没有嵌套的词法范围。使用global关键字使变量“动态”。您必须命名所有特殊变量。

$foo = 12;
$bar = 'hello';

function run() {
    global $foo,$bar;
    $foo = 13;
    $bar = 'bye';
}

run();
print "$foo, $bar\n"; // prints "13, bye"
Run Code Online (Sandbox Code Playgroud)

对于词法匿名函数,您需要使用use关键字命名所有变量并使用&它来引用它:

$foo = 12;
$bar = 'hello';

$run = function () use (&$foo,&$bar) {
    $foo = 13;
    $bar = 'bye';
};
call_user_func($run); 
print "$foo, $bar\n"; // prints "13, bye"
Run Code Online (Sandbox Code Playgroud)