首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在php中处理静态变量

问如何在php中处理静态变量
EN

Stack Overflow用户
提问于 2021-03-15 19:31:37
回答 1查看 35关注 0票数 1

我是php的初学者,想了解静态变量是如何工作的。我有一个函数,它包含一个常量变量"$ count“。当我多次调用函数时,静态变量在每次调用时都被初始化为"0“。我想要多次调用这个函数,记住常量变量达到的最后一个值是保留的。

代码语言:javascript
复制
$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();
EN

回答 1

Stack Overflow用户

发布于 2021-03-15 19:48:35

如果您稍微重新安排测试,您将更好地了解发生了什么。

代码语言:javascript
复制
$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();

结果

代码语言:javascript
复制
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>

静态变量仅在第一次看到它时被初始化,在本例中是函数的第一次调用。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66637168

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档