有没有可能有一个同时是递归和匿名的PHP函数?这是我试图让它工作,但它没有传入函数名。
$factorial = function( $n ) use ( $factorial ) {
if( $n <= 1 ) return 1;
return $factorial( $n - 1 ) * $n;
};
print $factorial( 5 );
我也意识到这是一种糟糕的实现阶乘的方式,这只是一个例子。
发布于 2010-03-20 04:03:10
为了使其正常工作,您需要将$factorial作为引用传递
$factorial = function( $n ) use ( &$factorial ) {
if( $n == 1 ) return 1;
return $factorial( $n - 1 ) * $n;
};
print $factorial( 5 );
发布于 2017-09-20 21:36:30
在更新版本的PHP中,您可以这样做:
$x = function($depth = 0) {
if($depth++)
return;
$this($depth);
echo "hi\n";
};
$x = $x->bindTo($x);
$x();
这可能会导致奇怪的行为。
发布于 2019-07-29 09:53:47
您可以在PHP 7.1+中使用Y组合符,如下所示:
function Y
($le)
{return
(function ($f)
{return
$f($f);
})(function ($f) use ($le)
{return
$le(function ($x) use ($f)
{return
$f($f)($x);
});
});
}
$le =
function ($factorial)
{return
function
($n) use ($factorial)
{return
$n < 2 ? $n
: $n * $factorial($n - 1);
};
};
$factorial = Y($le);
echo $factorial(1) . PHP_EOL; // 1
echo $factorial(2) . PHP_EOL; // 2
echo $factorial(5) . PHP_EOL; // 120
源代码来自:https://github.com/whitephp/the-little-phper/blob/master/src/chapter_9.php
https://stackoverflow.com/questions/2480179
复制相似问题