Rewriting an anonymous function in php 7.4

前端 未结 3 479
半阙折子戏
半阙折子戏 2021-01-03 00:19

There is the following anonymous recursive function:

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

echo $f(5); // 120
         


        
3条回答
  •  春和景丽
    2021-01-03 00:51

    I don't think you can rewrite the function as an arrow function.

    An arrow function will capture the value of any external variables by value at the time the function is created. But $f won't have a value until after the function is created and the variable is assigned.

    The original anonymous function solves this problem by capturing a reference to the variable with use (&$f), rather than use ($f). This way, it will be able to use the updated value of the variable that results from the assignment.

提交回复
热议问题