Saturday, March 24, 2007

Using static variables

Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.
static variable只作用于本地function内,在程序执行完后此变量值不会丢失,此方法再次调用,将使用上次操作完成后的此变量值。在singleton pattern里,也是利用static variable,使程序在运行期间只产生一个实例。


<?php
function Test_static_var()
{
static $a = 0;
echo $a, "<br />";
$a++;
}
Test_static_var();
Test_static_var();
Test_static_var();
?>
<?php
function Test()
{
static $count = 0;

$count++;
echo $count;
for($i = 0; $i < $count; $i++)
{
echo " ";
}
echo " before recursive <br />\n";
if ($count < 10) {
Test();
}
$count--;
echo $count;
for($i = 0; $i < $count; $i++)
{
echo " ";
}
echo " after recusive <br />\n";
}
Test();
// 1 before recursive
// 2 before recursive
// 3 before recursive
// 4 before recursive
// 5 before recursive
// 6 before recursive
// 7 before recursive
// 8 before recursive
// 9 before recursive
// 10 before recursive
// 9 after recusive
// 8 after recusive
// 7 after recusive
// 6 after recusive
// 5 after recusive
// 4 after recusive
// 3 after recusive
// 2 after recusive
// 1 after recusive
// 0 after recusive
?>

No comments :