有以下匿名递归函数:
$f = function($n) use (&$f) {
return ($n == 1) ? 1 : $n * $f($n - 1);
};
echo $f(5); // 120
我尝试重写到7.4版本,但出现错误,请告诉我缺少什么?
$f = fn($n) => ($n == 1) ? 1 : $n * $f($n - 1);
echo $f(5);
Notice: Undefined variable: f
Fatal error: Uncaught Error: Function name must be a string
最佳答案
正如 Barmar 所说,您不能从外部作用域使用 $f
,因为当隐式绑定(bind)发生时,$f
仍然是未定义的。
没有什么可以阻止您稍后将其作为参数传递。
$f = fn($f, $n) => $n == 1 ? 1 : $n * $f($f, $n - 1);
echo $f($f, 5); // 120
箭头函数的工作方式是,在定义期间,它们将使用外部作用域变量的按值绑定(bind)。
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. - https://wiki.php.net/rfc/arrow_functions_v2
闭包对变量$f
的赋值发生在闭包定义之后,并且变量$f
在它之前是未定义的。
据我所知,在定义箭头函数时没有任何通过引用绑定(bind)的机制。
关于php - 在 php 7.4 中重写匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58882959/