静态变量
$count = 5;
function get_count()
{
static $count = 0;
return $count++;
}
echo $count;
++$count;
echo get_count();
echo get_count();
我猜它输出5 0 1,这是对的,但我需要一个更好的解释?
$count = 5;
function get_count()
{
static $count = 0;
return $count++;
}
echo $count;
++$count;
echo get_count();
echo get_count();
我猜它输出5 0 1,这是对的,但我需要一个更好的解释?
函数中的变量与全局变量没有任何关系。static
关键字与C或Java中的关键字相同,这意味着:仅初始化此变量一次,并在函数结束时保持其状态。这意味着,当执行重新进入函数时,它会看到内部$count已被初始化,并在上次存储为 ,并使用该值。$count
$count
1
$count = 5; // "outer" count = 5
function get_count()
{
static $count = 0; // "inner" count = 0 only the first run
return $count++; // "inner" count + 1
}
echo $count; // "outer" count is still 5
++$count; // "outer" count is now 6 (but you never echoed it)
echo get_count(); // "inner" count is now + 1 = 1 (0 before the echo)
echo get_count(); // "inner" count is now + 1 = 2 (1 before the echo)
echo get_count(); // "inner" count is now + 1 = 3 (2 before the echo)
我希望这能理清思绪。