【问题标题】:How to deal with a static variable in php如何处理php中的静态变量
【发布时间】:2021-03-15 11:31:37
【问题描述】:

我是 php 的初学者,想了解静态变量的工作原理。我有一个函数,其中包含一个常量变量“$ count”。当我多次调用该函数时,静态变量在每次调用中都初始化为“0”。 我想多次调用这个函数,记住保持常量变量达到的最后一个值。

$x = 2; $y = "Level";

function hello(){
    global $x; global $y;
    static $count = 1;
    for(;;){
        if($count == 11)
            break;
        echo"/hello student_".$count." ".$y."_".$x,"<br>";
        $count++;
    }
}
hello();
hello();
hello();

【问题讨论】:

  • “当我多次调用该函数时,静态变量在每次调用中都初始化为“0”。” - 你在说什么?不它不是。第一次调用是1,第二次和第三次调用是11因为它是静态的。
  • 当我多次调用该函数时,静态变量在每次调用中都初始化为“0”不,不是,您在第一次调用时将其设置为1 .如果您注意到第二次和第三次呼叫没有输出任何内容,因为 $count 在第二次和第三次呼叫中仍然是 11,因此它会在第二次和第三次呼叫时立即爆发

标签: php static


【解决方案1】:

如果你稍微重新安排你的测试,你会更好地看到发生了什么

$x = 2; $y = "Level";

function hello(){
    global $x; global $y;
    static $count = 1;
    for(;;){
        if($count == 5) {
            echo 'I am out of here, $count is ' . $count . '<br>';
            break;
        }
        echo "hello student_".$count." ".$y."_".$x,'<br>';
        $count++;
    }
}
echo 'First call<br>';
hello();
echo 'Second call<br>';
hello();
echo 'Third call<br>';
hello();

结果

First call<br>
hello student_ Level_2<br>
hello student_1 Level_2<br>
hello student_2 Level_2<br>
hello student_3 Level_2<br>
hello student_4 Level_2<br>
I am out of here, $count is 5<br>
Second call<br>
I am out of here, $count is 5<br>
Third call<br>
I am out of here, $count is 5<br>

静态变量仅在第一次出现时才被初始化,在这种情况下是函数的第一次调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 2019-10-20
    • 2010-09-22
    • 1970-01-01
    • 2015-09-22
    • 2013-09-30
    • 1970-01-01
    相关资源
    最近更新 更多