【发布时间】: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