【问题标题】:Mutiple consecutive outputs instead of one in a function in PHP多个连续输出而不是 PHP 中的一个函数中的一个
【发布时间】:2021-06-11 00:22:00
【问题描述】:

我正在学习 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!

谢谢。

【问题讨论】:

    标签: php function scope static-variables


    【解决方案1】:

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

    为什么先写数字,后写文字?让我们打破函数的每次运行。为简化起见,我将仅使用 2 个调用的示例 (if ($count &lt; 2))

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

    【讨论】:

      【解决方案2】:

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

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

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

      这完全回答了你的问题吗?

      【讨论】:

        猜你喜欢
        • 2012-10-14
        • 1970-01-01
        • 2016-07-08
        • 1970-01-01
        • 2020-10-20
        • 1970-01-01
        • 2021-05-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多