Rewriting an anonymous function in php 7.4

前端 未结 3 406
半阙折子戏
半阙折子戏 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 think I just found one of the legitimate (no?) uses of $GLOBALS

    $f = fn ($n) =>($n == 1) ? 1 : $n * $GLOBALS['f']($n - 1);
    echo $f(5); // 120
    

    Sidenote: what if $n < 1 ?

提交回复
热议问题