Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

closures - Rewriting an anonymous function in php 7.4

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...