加拿大华人论坛 美国华人新闻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; } ?>

  ·生活百科 太阳能户外 LED 灯条
·生活百科 受控负载

美国华人新闻-加拿大

富坚义博开通推特

华人网摘要:经漫画家村田雄介和集英社确认,该账号为富坚本人。 图源:twitter 5月23日,推上出现了一个ID为富坚义博的新账号,简介上写着这是一个报告原稿进度的“官方()”并发布了一 ...

美国华人新闻-加拿大

日本议员提议立法禁止AV

华人网摘要:日本立宪民主党众议员堤かなめ在25日众议院内阁委员会上表示,立宪民主党将 "禁止涉及性行为的色情制品 "为目标制定法律。 日本立宪民主党众议员堤かなめ在25日众议院内阁 ...

美国华人新闻-加拿大

师村妙石的创新篆刻作品

华人网摘要:师村妙石,日本著名艺术家、篆刻家、书法家,一直致力于中日友好活动和文化交流,长期专攻中国传统篆刻技法。师村妙石先生曾223次访问中国进行书法研究和文化交流(截至 ...

日本,每年一次全民体检
美国华人新闻-加拿大

日本,每年一次全民体检

华人网关注我,带你看看普通人的日本生活。我家附近每隔两三百米就有一块告示板,类似于国内“居委会”或者“社区”的通知,平时大事小情都能在这里看到。前几天看到了有免费筛查宫 ...

美国华人新闻-加拿大

师村妙石的编著书影

华人网摘要:师村妙石,日本著名艺术家、篆刻家、书法家,一直致力于中日友好活动和文化交流,长期专攻中国传统篆刻技法。师村妙石先生曾223次访问中国进行书法研究和文化交流(截至 ...