PHP的静态变量介绍

<p>静态变量只存在于函数作用域内,也就是说,静态变量只存活在栈中。一般的函数内变量在函数结束后会释放,比如局部变量,但是静态变量却不会。就是说,下次再调用这个函数的时候,该变量的值会保留下来。</p><p>只要在变量前加上关键字static,该变量就成为静态变量了。</p><pre class="brush:php;toolbar:false">&lt;?php functiontest() { static$nm=1; $nm=$nm*2; print$nm.&quot;&lt;br/&gt;&quot;; } //第一次执行,$nm=2 test(); //第一次执行,$nm=4 test(); //第一次执行,$nm=8 test(); ?&gt;</pre><p>程序运行结果:</p><p>函数test()执行后,变量$nm的值都保存了下来了。</p><p>在class中经常使用到静态属性,比如静态成员、静态方法。</p><p>Program List:类的静态成员</p><p>静态变量$nm属于类nowamagic,而不属于类的某个实例。这个变量对所有实例都有效。</p><p>::是作用域限定操作符,这里用的是self作用域,而不是$this作用域,$this作用域只表示类的当前实例,self::表示的是类本身。</p><pre class="brush:php;toolbar:false">&lt;?php classnowamagic { publicstatic$nm=1; functionnmMethod() { self::$nm+=2; echoself::$nm.&#39;&lt;br/&gt;&#39;; } } $nmInstance1=newnowamagic(); $nmInstance1-&gt;nmMethod(); $nmInstance2=newnowamagic(); $nmInstance2-&gt;nmMethod(); ?&gt;</pre><p>程序运行结果:</p><p>Program List:静态属性</p><pre class="brush:php;toolbar:false">&lt;?php classNowaMagic { publicstatic$nm=&#39;www.nowamagic.net&#39;; publicfunctionnmMethod() { returnself::$nm; } } classArticleextendsNowaMagic { publicfunctionarticleMethod() { returnparent::$nm; } } //通过作用于限定操作符访问静态变量 printNowaMagic::$nm.&quot;&lt;br/&gt;&quot;; //调用类的方法 $nowamagic=newNowaMagic(); print$nowamagic-&gt;nmMethod().&quot;&lt;br/&gt;&quot;; printArticle::$nm.&quot;&lt;br/&gt;&quot;; $nmArticle=newArticle(); print$nmArticle-&gt;nmMethod().&quot;&lt;br/&gt;&quot;; ?&gt;</pre><p>程序运行结果:</p><p>www.nowamagic.net</p><p>www.nowamagic.net</p><p>www.nowamagic.net</p><p>www.nowamagic.net</p><p>Program List:简单的静态构造器</p><p>PHP没有静态构造器,你可能需要初始化静态类,有一个很简单的方法,在类定义后面直接调用类的Demonstration()方法。</p><pre class="brush:php;toolbar:false">&lt;?php functionDemonstration() { return&#39;Thisistheresultofdemonstration()&#39;; } classMyStaticClass { //publicstatic$MyStaticVar=Demonstration();//!!!FAILS:syntaxerror publicstatic$MyStaticVar=null; publicstaticfunctionMyStaticInit() { //thisisthestaticconstructor //becauseinafunction,everythingisallowed,includinginitializingusingotherfunctions self::$MyStaticVar=Demonstration(); } }MyStaticClass::MyStaticInit();//Callthestaticconstructor echoMyStaticClass::$MyStaticVar; //Thisistheresultofdemonstration() ?&gt;</pre><p>程序运行结果:</p><p>1</p><p>This is the result of demonstration()</p>
返回顶部 留言