在 php 7.4 中重写匿名函数 [英] Rewriting an anonymous function in php 7.4

查看:40
本文介绍了在 php 7.4 中重写匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有如下匿名递归函数:

$f = function($n) use (&$f) {返回 ($n == 1) ?1 : $n * $f($n - 1);};回声 $f(5);//120

我尝试重写到 7.4 版本,但出现错误,请告诉我缺少什么?

$f = fn($n) =>($n == 1) ?1 : $n * $f($n - 1);回声 $f(5);

<块引用>

注意:未定义变量:f

致命错误:未捕获的错误:函数名必须是字符串

解决方案

正如 Barmar 所说,你不能在作用域外使用 $f,因为当隐式绑定发生时 $f 仍未定义.

没有什么可以阻止您稍后将其作为参数传递.

$f = fn($f, $n) =>$n == 1 ?1 : $n * $f($f, $n - 1);回声 $f($f, 5);//120

箭头函数的工作方式是,在定义期间,它们将使用外部作用域变量的按值绑定.

<块引用>

如前所述,箭头函数使用按值变量绑定.这大致相当于对箭头函数中使用的每个变量 $x 执行 use($x).- https://wiki.php.net/rfc/arrow_functions_v2

闭包对变量 $f 的赋值发生在闭包定义之后,而变量 $f 在它之前是未定义的.

据我所知,在定义箭头函数时没有任何通过引用绑定的机制.

There is the following anonymous recursive function:

$f = function($n) use (&$f) {
    return ($n == 1) ? 1 : $n * $f($n - 1);
};

echo $f(5); // 120

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);

Notice: Undefined variable: f

Fatal error: Uncaught Error: Function name must be a string

解决方案

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.

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆