Home > php教程 > php手册 > body text

PHP static静态变量详解

WBOY
Release: 2016-06-21 08:53:29
Original
1139 people have browsed it

PHP static静态变量

变量范围的另一个重要特性是静态变量(static variable)。静态变量仅在局部函数域中存在,但当程序执行离开此作用域时,其值并不丢失。看看下面的例子:

例子 演示需要静态变量的例子

<ol class="dp-xml">
<li class="alt"><span><span class="tag"></span><span class="tag-name">PHP</span><span> </span></span></li>
<li><span>   function Test()  </span></li>
<li class="alt"><span>   {  </span></li>
<li>
<span>   $</span><span class="attribute">w3sky</span><span> = </span><span class="attribute-value">0</span><span>;  </span>
</li>
<li class="alt"><span>   echo $w3sky;  </span></li>
<li><span>   $w3sky++;  </span></li>
<li class="alt"><span>   }  </span></li>
<li>
<span>   </span><span class="tag">?></span><span> </span>
</li>
</ol>
Copy after login

本函数没什么用处,因为每次调用时都会将 $w3sky 的值设为 0 并输出 "0"。将变量加一的 $w3sky++ 没有作用,因为一旦退出本函数则变量 $w3sky 就不存在了。要写一个不会丢失本次计数值的计数函数,要将变量 $w3sky 定义为静态的:


例子 使用静态变量的例子

<ol class="dp-xml">
<li class="alt"><span><span class="tag"></span><span class="tag-name">PHP</span><span> </span></span></li>
<li><span>   function Test()  </span></li>
<li class="alt"><span>   {  </span></li>
<li>
<span>   static $</span><span class="attribute">w3sky</span><span> = </span><span class="attribute-value">0</span><span>;  </span>
</li>
<li class="alt"><span>   echo $w3sky;  </span></li>
<li><span>   $w3sky++;  </span></li>
<li class="alt"><span>   }  </span></li>
<li>
<span>   </span><span class="tag">?></span><span> </span>
</li>
</ol>
Copy after login


现在,每次调用 Test() 函数都会输出 $w3sky 的值并加一。



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!