PHP 手册示例 #6 具有递归函数变化范围的静态变量理解


PHP Manual Example #6 Static variables with recursive functions variation scope understanding

提前道歉(新手在这里),但试图理解并很难找到与此直接相关的主题。我从 php 手册中制作了示例 #6 带有递归函数的静态变量的变体

http://php.net/manual/en/language.variables.scope.php

<?php
    function test() {
        static $count = 0;
        $count++;
        echo $count;
        if ($count < 10) {
            test();
        }
        $count--;
        echo $count;
    }
    
    test();
?>

输出123456789109876543210

我希望它在 if 语句之外转到 9 并递减后停止。(例如)123456789109

我显然不了解静态范围和代码流。我真的应该弄清楚一个调试器,但是有什么指示吗?

也许这个小修改可以帮助你更好地理解。

为什么它在 if 语句之外转到 9 后不停止?

因为每次调用测试都会运行测试直到最后。它递增 10 倍,递减 10 倍。由于 10 次测试调用,第一次增加 10 次,在第 10 次调用中开始脱水泥。第 10 个调用完成,第 9 个调用递减。第 9 个调用已完成,第 8 个调用递减。

<?php
function test()
{
    static $count = 0;
    $count++;
    echo $count.". call of test() (output after incrementing)<br />";
    if ($count < 10) {
        test();
    }
    echo $count.". call of test() (output before decrementing)<br />";
    $count--;
}
test();
?>

输出:

1. call of test() (output after incrementing)
2. call of test() (output after incrementing)
3. call of test() (output after incrementing)
4. call of test() (output after incrementing)
5. call of test() (output after incrementing)
6. call of test() (output after incrementing)
7. call of test() (output after incrementing)
8. call of test() (output after incrementing)
9. call of test() (output after incrementing)
10. call of test() (output after incrementing)
10. call of test() (output before decrementing)
9. call of test() (output before decrementing)
8. call of test() (output before decrementing)
7. call of test() (output before decrementing)
6. call of test() (output before decrementing)
5. call of test() (output before decrementing)
4. call of test() (output before decrementing)
3. call of test() (output before decrementing)
2. call of test() (output before decrementing)
1. call of test() (output before decrementing)