在本函数没什么用处,因为每次调用时都会将 $w3sky 的值设为 0 并输出 "0"。将变量加一的 $w3sky++ 没有作用,因为一旦退出本函数则变量 $w3sky 就不存在了。要写一个不会丢失本次计数值的计数函数,要将变量 $w3sky 定义为静态的:
例子 使用PHP静态变量static的例子
<ol class="dp-xml"> <li class="alt"><span><span class="tag"><span> ?PHP </span></span></span></li> <li><span>function Test(){ </span></li> <li class="alt"> <span>static $</span><span class="attribute">w3sky</span><span> = </span><span class="attribute-value">0</span><span>; </span> </li> <li><span>echo $w3sky; </span></li> <li class="alt"><span>$w3sky++; </span></li> <li><span>} </span></li> <li class="alt"> <span class="tag">?></span><span> </span> </li> </ol>
现在,每次调用 Test() 函数都会输出 $w3sky 的值并加一。
静态变量也提供了一种处理递归函数的方法。递归函数是一种调用自己的函数。写递归函数时要小心,因为可能会无穷递归下去。必须确保有充分的方法来中止递归。一下这个简单的函数递归计数到 10,使用静态变量 $count 来判断何时停止:
例子 PHP静态变量static与递归函数
<ol class="dp-xml"> <li class="alt"><span><span class="tag"><span> ?PHP </span></span></span></li> <li><span>function Test(){ </span></li> <li class="alt"> <span>static $</span><span class="attribute">count</span><span> = </span><span class="attribute-value">0</span><span>; </span> </li> <li><span>$count++; </span></li> <li class="alt"><span>echo $count; </span></li> <li> <span>if ($count </span><span class="tag"><span> </span><span class="tag-name">10</span><span>) { </span></span> </li> <li class="alt"><span>Test(); </span></li> <li><span>} </span></li> <li class="alt"><span>$count--; </span></li> <li><span>} </span></li> <li class="alt"> <span class="tag">?></span><span> </span> </li> </ol>
注: 静态变量可以按照上面的例子声明。如果在声明中用表达式的结果对其赋值会导致解析错误。
例子 声明PHP静态变量static
<ol class="dp-xml"> <li class="alt"><span><span class="tag"><span> ?PHP </span></span></span></li> <li><span>function foo(){ </span></li> <li class="alt"> <span>static $</span><span class="attribute">int</span><span> = </span><span class="attribute-value">0</span><span>;// correct </span> </li> <li> <span>static $</span><span class="attribute">int</span><span> = </span><span class="attribute-value">1</span><span>+2; // wrong (as it is an expression_r_r) </span> </li> <li class="alt"> <span>static $</span><span class="attribute">int</span><span> = </span><span class="attribute-value">sqrt</span><span>(121); // wrong (as it is an expression_r_r too) </span> </li> <li><span>$int++; </span></li> <li class="alt"><span>echo $int; </span></li> <li><span>} </span></li> <li class="alt"> <span class="tag">?></span><span> </span> </li> </ol>