如何在PHP函数中获取当前递归级别
如何在PHP函数中获取当前递归级别?我的意思是,有没有像这样的“神奇”(或最终正常)功能:如何在PHP函数中获取当前递归级别,php,recursion,Php,Recursion,如何在PHP函数中获取当前递归级别?我的意思是,有没有像这样的“神奇”(或最终正常)功能: function doSomething($things) { if (is_array($things)) { foreach ($things as $thing) { doSomething($thing); } } else { // This is what I want : echo cur
function doSomething($things) {
if (is_array($things)) {
foreach ($things as $thing) {
doSomething($thing);
}
} else {
// This is what I want :
echo current_recursion_level();
}
}
我知道我可以使用另一个函数参数($level
,在本例中):
但我想知道是否有一个内置的函数(或技巧)可以做到这一点。可能是使用了debug\u backtrace()
,但它似乎不是一个简单或快速的解决方案
我没有找到这个信息,也许它根本不存在…你需要自己计算,唯一的选择是像XDebug这样的东西,它可以描述你的整个软件。但这是非常低效的
<?php
function my_recursive_fn($param) {
static $counter = 0;
if (is_array($param)) {
++$counter;
foreach ($param as $k => $v) {
}
}
else {
echo $counter;
--$counter;
// If we're returning (only PHP 5.5+)
try {
return $counter;
}
finally {
--$counter;
}
}
}
?>
在java中,您可以检查调用堆栈。我认为在php中也可以这样做:
这就是你要找的吗
由于php不使用尾部调用优化递归,这应该告诉您递归的深度。如果您只是想避免达到php的100级递归限制,那么
count(debug_backtrace());
应该足够了。否则,您没有选择传递深度参数,尽管precrement操作符使其更清晰,如下面的示例所示
function recursable ( $depth = 0 ) {
if ($depth > 3) {
debug_print_backtrace();
return true;
} else {
return recursable( ++$depth );
}
}
private函数选择($modules,$level=0)
{
$return_html='';
$level_html='';
$new_level=0;
foreach($modules作为$module)
{
$repeat=str_repeat(“”,$level);
如果(!empty($module['children']))
{
$return_html.='.$repeat'.$module['title'.';
$new_level=$level+1;
$return\u html.=$this->select($module['children',$new\u level);
}
其他的
{
$return_html.='.$repeat'.$module['title'.';
}
}
return$return\u html;
}
使用静态变量。使用static
检查可以,但您计算的是数组元素的总数,而不是递归级别。要执行后一种操作,只需在函数开始处增加变量,然后在返回之前减少它。在返回之前是否需要减少$counter
?当然,要更正它以真正计算递归。OP在循环中有递增。为什么递减?函数实际上被调用了。高度依赖于用例。因为当您返回时,您不再处于更高的递归级别。下次从头开始递归时,递归级别应再次从0开始。在调用函数后,您需要减少$level。仅供参考,递归限制不是来自PHP,而是来自Xdebug扩展
count(debug_backtrace());
function recursable ( $depth = 0 ) {
if ($depth > 3) {
debug_print_backtrace();
return true;
} else {
return recursable( ++$depth );
}
}
private function select($modules, $level = 0)
{
$return_html = '';
$level_html = '';
$new_level = 0;
foreach($modules as $module)
{
$repeat = str_repeat(' ', $level);
if(!empty($module['children']))
{
$return_html .= '<option>'.$repeat.' '.$module['title'].'</option>';
$new_level = $level+1;
$return_html .= $this->select($module['children'], $new_level);
}
else
{
$return_html .= '<option>'.$repeat.' '.$module['title'].'</option>';
}
}
return $return_html;
}