PHP的static静态变量

静态变量只存在于函数作用域内,也就是说,静态变量只存活在栈中。一般的函数内变量在函数结束后会释放,比如局部变量,但是静态变量却不会。就是说,下次再调用这个函数的时候,该变量的值会保留下来。

只要在变量前加上关键字static,该变量就成为静态变量了。

01 <?php
02     function test()
03     {
04         static $nm = 1;
05         $nm $nm * 2;
06         print $nm."<br />";
07     }
08      
09     // 第一次执行,$nm = 2
10     test();
11     // 第一次执行,$nm = 4
12     test();
13     // 第一次执行,$nm = 8
14     test();
15 ?>

程序运行结果:

1 2
2 4
3 8

函数test()执行后,变量$nm的值都保存了下来了。

在class中经常使用到静态属性,比如静态成员、静态方法。

Program List:类的静态成员

静态变量$nm属于类nowamagic,而不属于类的某个实例。这个变量对所有实例都有效。

::是作用域限定操作符,这里用的是self作用域,而不是$this作用域,$this作用域只表示类的当前实例,self::表示的是类本身。

01 <?php
02     class nowamagic
03     {
04         public static $nm = 1;
05          
06         function nmMethod()
07         {
08             self::$nm += 2;
09             echo self::$nm '<br />';
10         }
11     }
12      
13     $nmInstance1 new nowamagic();
14     $nmInstance1 -> nmMethod();
15      
16     $nmInstance2 new nowamagic();
17     $nmInstance2 -> nmMethod();
18 ?>

程序运行结果:

1 3
2 5

转自:http://www.nowamagic.net/php/php_StaticVariable.php

猜你喜欢

转载自710542316.iteye.com/blog/2269999