时间:2021-07-01 10:21:17 帮助过:17人阅读
只要在变量前加上关键字static,该变量就成为静态变量了。
- <!--?php
- function test()
- {
- static $nm = 1;
- $nm = $nm * 2;
- print $nm."<br /-->";
- }
- // 第一次执行,$nm = 2
- test();
- // 第一次执行,$nm = 4
- test();
- // 第一次执行,$nm = 8
- test();
- ?>
程序运行结果:
2
4
8
函数test()执行后,变量$nm的值都保存了下来了。
在class中经常使用到静态属性,比如静态成员、静态方法。
Program List:类的静态成员
静态变量$nm属于类nowamagic,而不属于类的某个实例。这个变量对所有实例都有效。
::是作用域限定操作符,这里用的是self作用域,而不是$this作用域,$this作用域只表示类的当前实例,self::表示的是类本身。
view source
print?
- <!--?php
- class nowamagic
- {
- public static $nm = 1;
- function nmMethod()
- {
- self::$nm += 2;
- echo self::$nm . '<br /-->';
- }
- }
- $nmInstance1 = new nowamagic();
- $nmInstance1 -> nmMethod();
- $nmInstance2 = new nowamagic();
- $nmInstance2 -> nmMethod();
- ?>
程序运行结果:
3
5