PHP 中函数中的多个连续输出而不是一个

Mutiple consecutive outputs instead of one in a function in PHP

我正在学习 PHP 中的 static 变量,并在 PHP 手册中看到了这段代码。


<?php
function test() {
    static $count = 0;

    $count++;
    echo $count;
    if ($count < 10) {
        test();
    }
    $count--;
}
?>

我无法理解最后一个 $count--; 的目的。所以,我在下面写了一个不同版本的函数:

<?php

function test() {
    static $count = 0;

    $count++;

    echo $count;
    if ($count < 10) {
        test();
    }
    echo 'I am here!';

    $count--;
}

test();
?>

以上代码的输出为:

12345678910I am here!I am here!I am here!I am here!I am here!I am here!I am here!I am here!I am here!I am here!

为什么输出不只是下面一行,因为我们只超过了 if 条件一次。

12345678910I am here!

如果我们多次超过 if 条件,那么输出不应该是:

1I am here!2I am here!3I am here!4I am here!5I am here!6I am here!7I am here!8I am here!9I am here!10I am here!

谢谢。

这更多的是关于递归而不是静态变量。然而:

为什么先写数字再写文字?让我们打破函数的每个 运行 。为了简单起见,我将仅使用带有 2 个调用的示例 (if ($count < 2))

  • 第一个调用开始,$count递增到1
    • 打印1
  • 在第一次调用中,满足条件 $count < 2,因此它调用 test()(因此这将是第二次调用)
  • 第二次调用开始,$count 增加到 2(如果它不是静态的,它不会保留更高范围的值)
    • 打印2
  • 在第二次调用中,条件 $count < 2 不满足,因此它跳过 if
    • 打印I am here!并结束第二次调用
  • 现在第一次调用已完成 运行递归函数因此它继续
    • 打印I am here!并结束第一次调用

当您在方法中调用 test() 时,不会停止该方法中其余代码的执行。

据我所知,它没有在每个字符串“我在这里”之后输出数字的原因是您在输出之前调用了方法 test()。所以每次它都在等待该方法完成,然后再继续下一个字符串。

如果您将 $count 回显移动到它之后,我相信它会按预期输出。

这是否完全回答了您的问题?