加拿大华人论坛 美国华人新闻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; } ?>
·加拿大新闻 宝马出新款手动M2,向经典致敬
·加拿大新闻 惊爆!加拿大一年15.3万次医疗事故!这6种伤害最常见,要多住
·加拿大新闻 温哥华中国电影周开幕光影交流对话中国
·加拿大新闻 奥迪首款电动轿跑E5Sportback,闪耀登陆津门
·加拿大新闻 震惊:加拿大参议员做手术,未经同意竟被切除子宫
·中文新闻 Yungblud 将把 IDOLS 世界巡回演唱会带到澳大利亚
·中文新闻 凯蒂·佩里 (Katy Perry) 打破了对与贾斯汀·特鲁多 (Justin Trudeau) 的