本文介绍了匿名递归PHP函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可能有一个递归和匿名的PHP函数?这是我试图让它工作,但它不通过函数名称。

Is it possible to have a PHP function that is both recursive and anonymous? This is my attempt to get it to work, but it doesn't pass in the function name.

$factorial = function( $n ) use ( $factorial ) {
    if( $n <= 1 ) return 1;
    return $factorial( $n - 1 ) * $n;
};
print $factorial( 5 );

我也知道这是一个糟糕的方法来实现阶乘,它只是一个例子。 / p>

I'm also aware that this is a bad way to implement factorial, it's just an example.

推荐答案

为了工作,你需要传递$ factorial作为参考

In order for it to work, you need to pass $factorial as a reference

$factorial = function( $n ) use ( &$factorial ) {
    if( $n == 1 ) return 1;
    return $factorial( $n - 1 ) * $n;
};
print $factorial( 5 );

这篇关于匿名递归PHP函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-20 10:03