匿名递归 PHP 函数 [英] Anonymous recursive PHP functions

查看:33
本文介绍了匿名递归 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 );

我也知道这是实现阶乘的不好方法,这只是一个例子.

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 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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