具有意外输出的其他循环

Other loop with unexpected output

我有这段代码,但我不明白输出结果。我期待输出 121。 我想了解这个特定函数而不是阶乘函数。

代码:

function a($num) {
    static $totFac = 1;

    if($num > 0){
        $totFac = $totFac * $num;
        a($num - 1);
    }

    $totFac++;
    return $totFac;
}

$result = a(5);
echo 'result: '.$result;

输出:

126
  • 首先,5的阶乘为120解释为:

    5! = 5 x 4 x 3 x 2 x 1 = 120
    
  • 其次,递归调用时阶乘应该是这样的:

    function factorial($number) {
        if ($number < 2) { 
            return 1; 
        } else { 
            return ($number * factorial($number-1)); 
        } 
    }
    
  • 如果你不是指阶乘,那么如果我改变你的函数就会发生这种情况

    function a($num) {
        static $totFac = 1;
    
        if($num > 0){
            $totFac = $totFac * $num;
            echo "calc totFac: " . $totFac . "\n";
            a($num - 1);
        }
    
        $totFac++;
        echo "increment totFac: " . $totFac . "\n";
       return $totFac;
    }
    
    $result = a(5);
    echo 'result: '.$result;
    

这是回显的输出

calc totFac: 5
calc totFac: 20
calc totFac: 60
calc totFac: 120
calc totFac: 120
increment totFac: 120
increment totFac: 121
increment totFac: 122
increment totFac: 123
increment totFac: 124
increment totFac: 125
result: 126
<?php
function a($num) {
    static $totFac = 1;
    if($num > 0){
        $totFac = $totFac * $num;
        echo 'totfac: '.$totFac . "<br>";
        return a($num - 1); //you have to return here to stop execution
    } else {
        $totFac++;
        return $totFac;
    }
}
$result = a(5);
echo 'result: '.$result;
?>

看评论解释