在箭头函数中通过引用使用变量
Use variable by reference in arrow function
PHP 7.4 引入 Arrow functions。它还引入了隐式按值范围绑定,从而消除了对 use
关键字的需要。
现在,如果我们想通过常规匿名函数引用来使用闭包作用域外的变量,我们会这样做:
$num = 10;
call_user_func(function() use (&$num) {
$num += 5;
});
echo $num; // Output: 15
但是使用箭头函数似乎是不可能的
$num = 10;
call_user_func(fn() => $num += 5);
echo $num; // Output: 10
那么如何通过引用使用$num
变量?
阅读有关它的documentation,它说...
By-value variable binding
As already mentioned, arrow functions use by-value variable binding. This is roughly equivalent to
performing a use($x) for every variable $x used inside the arrow
function. A by-value binding means that it is not possible to modify
any values from the outer scope:
$x = 1;
$fn = fn() => $x++; // Has no effect
$fn();
var_dump($x); // int(1)
所以不可能是ATM。
PHP 7.4 引入 Arrow functions。它还引入了隐式按值范围绑定,从而消除了对 use
关键字的需要。
现在,如果我们想通过常规匿名函数引用来使用闭包作用域外的变量,我们会这样做:
$num = 10;
call_user_func(function() use (&$num) {
$num += 5;
});
echo $num; // Output: 15
但是使用箭头函数似乎是不可能的
$num = 10;
call_user_func(fn() => $num += 5);
echo $num; // Output: 10
那么如何通过引用使用$num
变量?
阅读有关它的documentation,它说...
By-value variable binding
As already mentioned, arrow functions use by-value variable binding. This is roughly equivalent to performing a use($x) for every variable $x used inside the arrow function. A by-value binding means that it is not possible to modify any values from the outer scope:$x = 1; $fn = fn() => $x++; // Has no effect $fn(); var_dump($x); // int(1)
所以不可能是ATM。