用静态变量解释递归函数PHP

Explain recursive function with static variable PHP

请帮我理解这个例子?
为什么它打印十次“10”?为什么不是 0 1 2 3 4 5 6 7 8 9?

<?php
function test()
{
    static $count = 0;
    $count++;
    if ($count < 10) {
        test();
    }
    echo "\n$count";
}
test();

如果小于10就递归不输出,当10就落到echo,每次递归10次就打印10,每次退出。

如果您 echo 在递归之前,它将按照您描述的那样工作。另外,你需要在递增之前输出,否则你不会得到 0:

function test()
{
    static $count = 0;
    echo "\n$count";

    $count++;
    if ($count < 10) {
        test();
    }

}
test();