有没有办法通过引用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'.
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)
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |