我是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();发布于 2021-03-15 19:48:35
如果您稍微重新安排测试,您将更好地了解发生了什么。
$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>静态变量仅在第一次看到它时被初始化,在本例中是函数的第一次调用。
https://stackoverflow.com/questions/66637168
复制相似问题