加拿大华人论坛 美国华人新闻Using static variables in PHP
在加拿大
Using static variablesAnother 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. Consider the following example:Example 12-5. Example demonstrating need for static variables<?phpfunction Test(){ $a = 0; echo $a; $a++;}?>This function is quite useless since every time it is called it sets $a to 0 and prints "0". The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:Example 12-6. Example use of static variables<?phpfunction Test(){ static $a = 0; echo $a; $a++;}?>Now, every time the Test() function is called it will print the value of $a and increment it.Static variables also provide one way to deal with recursive functions. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $count to know when to stop:Example 12-7. Static variables with recursive functions<?phpfunction Test(){ static $count = 0; $count++; echo $count; if ($count < 10) { Test(); } $count--;}?> Note: Static variables may be declared as seen in the examples above. Trying to assign values to these variables which are the result of expressions will cause a parse error. Example 12-8. Declaring static variables <?php function foo(){ static $int = 0; // correct static $int = 1+2; // wrong (as it is an expression) static $int = sqrt(121); // wrong (as it is an expression too) $int++; echo $int; } ?>
·中文新闻 澳大利亚反犹太主义:新南威尔士州警方称 Woollahra 破坏行为“
·中文新闻 出于福利考虑,医院取消了见习妇产科医生的资格