递归函数 PHP 中的返回值问题


Issue with returning value in recursive function PHP

在递归函数中返回值时遇到一些问题。但我可以附和它。这可能有什么问题?

function calculate($i,$count=1)
{
    $str_i = (string)$i;
    $rslt = 1;
    for ($k=0; $k<strlen($str_i); $k++) {
        $rslt = $str_i[$k]*$rslt;
    }
    if ( strlen((string)$rslt) > 1 ) {
        $this->calculate($rslt,++$count);
    } elseif ( strlen((string)$rslt) == 1 ) {
        return $count;  
    }
}

在代码的if中,不使用递归调用中返回的值。您不会将其设置为值或return它。因此,除基本情况外,每个调用都不返回值。

试试这个:

function calculate($i,$count=1)
{
    $str_i = (string)$i;
    $rslt = 1;
    for ($k=0; $k<strlen($str_i); $k++) {
        $rslt = $str_i[$k]*$rslt;
    }
    if ( strlen((string)$rslt) > 1 ) {
        return $this->calculate($rslt,$count+1); // I changed this line
    } elseif ( strlen((string)$rslt) == 1 ) {
        return $count;  
    }
}

现在我们返回递归调用返回的值。注意我++$count更改为$count+1,因为在使用递归时改变是不好的风格。