php static 变量的例子
变量范围的另一个重要特性是静态变量(static variable),静态变量仅在局部函数域中存在,但当程序执行离开此作用域时,其值并不丢失,看看下面的例子:
- class test
- {
- public static function a(){}
- public function b(){}
- }
- $obj = new test;
-
- test::a();
- $obj->a();
- $obj->b();
例子,演示需要静态变量的例子:
- <?php
- class myobject {
- public static $mystaticvar = 0;
- function mymethod() {
-
-
-
- self::$mystaticvar += 2;
- echo self::$mystaticvar . "<br />";
- }
- }
- $instance1 = new myobject();
- $instance1->mymethod();
- $instance2 = new myobject();
- $instance2->mymethod();
- ?>
- <?php
- class myobject {
- public static $myvar = 10;
- }
- echo myobject::$myvar;
-
- ?>
本函数没什么用处,因为每次调用时都会将 $w3sky 的值设为 0 并输出 "0",将变量加一的 $w3sky++ 没有作用,因为一旦退出本函数则变量 $w3sky 就不存在了,要写一个不会丢失本次计数值的计数函数,要将变量 $w3sky 定义为静态的:
例子,使用静态变量的例子:
- <?php
- function test()
- {
- static $w3sky = 0;
- echo $w3sky;
- $w3sky++;
- }
- ?>
现在,每次调用 test() 函数都会输出 $w3sky 的值并加一.看个实例:
- <?php
- class foo
- {
- public static $my_static = 'foo';
- public function staticvalue() {
- return self::$my_static;
- }
- }
- class bar extends foo
- {
- public function foostatic() {
- return parent::$my_static;
- }
- }
- print foo::$my_static . "n";
- $foo = new foo();
- print $foo->staticvalue() . "n";
- print $foo->my_static . "n";
- print $foo::$my_static . "n";
- $classname = 'foo';
- print $classname::$my_static . "n";
- print bar::$my_static . "n";
- $bar = new bar();
- print $bar->foostatic() . "n";
- ?>