在PHP 7.4中重写匿名函数 [英] Rewriting an anonymous function in php 7.4
问题描述
有以下匿名递归函数:
$f = function($n) use (&$f) {
return ($n == 1) ? 1 : $n * $f($n - 1);
};
echo $f(5); // 120
我尝试重写为7.4版,但是出现错误,请告诉我我所缺少的内容吗?
I try to rewrite to version 7.4, but there is an error, please tell me what I'm missing?
$f = fn($n) => ($n == 1) ? 1 : $n * $f($n - 1);
echo $f(5);
注意:未定义的变量:f
Notice: Undefined variable: f
致命错误:未捕获错误:函数名称必须是字符串
Fatal error: Uncaught Error: Function name must be a string
推荐答案
就像Barmar所说的那样,您不能从外部范围使用$f
,因为隐式绑定发生时$f
仍未定义.
Just like Barmar said, you can't use $f
from the outside scope, because when the implicit binding takes place $f
is still undefined.
没有什么可以阻止您以后将其作为参数传递.
There is nothing stopping you from passing it later as a parameter.
$f = fn($f, $n) => $n == 1 ? 1 : $n * $f($f, $n - 1);
echo $f($f, 5); // 120
箭头功能的工作方式是,在定义期间,它们将使用外部作用域变量的按值绑定.
The way arrow functions work, is that during definition time they will use by-value binding of the outer scope's variables.
如前所述,箭头函数使用按值变量绑定.这大致等效于对箭头函数内部使用的每个变量
$x
执行use($x)
. - https://wiki.php.net/rfc/arrow_functions_v2
将闭包分配给变量$f
的操作发生在闭包的定义之后,而变量$f
在其定义之前未定义.
The assignment of the closure to the variable $f
happens after closure's definition and the variable $f
is undefined prior to it.
据我所知,在定义箭头函数时,没有任何机制可以通过引用进行绑定.
As far as I am aware, there isn't any mechanism to bind by reference while defining arrow functions.
这篇关于在PHP 7.4中重写匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!