PHP的static变量初始化问题
知识点:一、static变量只能使用使用基本类型的字面值赋值,通过表达式、对象或函数返回值赋值的操作都是不允许的
二、静态变量声明是在编译时解析的
下面看几个例子。
1.类中的static成员变量
class Test {public static $t = array('asdf', 1234);public function __construct() {echo "ok/n";}function hi() {echo "hello/n";}}
class TestWithImproperStatement {// public static $str = new Test(); // error, syntax error, unexpected 'new'function hi() {echo "hello";}}
上面两段代码均含有static成员变量,但是第二个类如果打开注释部分,就会出现编译错误,因为 new Test(); 不是基本类型字面值。
2.函数中的成员变量
/*** Note: Static declarations are resolved in compile-time. * * @return Test*/function mytest1() {// static $test = new Test(); // Parse error: syntax error, unexpected T_NEW// static $int = 1+2; // wrong(as it is an expression)// static $int = sqrt(121);// wrong(as it is an expression too)return $test;}/*** @return Test*/function mytest2() {static $test = null;if (!$test) {$test = new Test();}echo 'mytest2 ';return $test;}/*** @return Test*/function mytest3() {static $test = null;$test = new Test();echo 'mytest3 ';return $test;}
mytest1 注释掉的代码就是编译出错的部分,错误原因与上面例子描述相同,这里我们着重看下 mytest2 和 mytest3,运行下面代码:
mytest2()->hi();mytest2()->hi();mytest2()->hi();mytest3()->hi();mytest3()->hi();mytest3()->hi();/* 代码输出结果okmytest2 hellomytest2 hellomytest2 hellookmytest3 hellookmytest3 hellookmytest3 hello*/
从运行结果中可以看出,static 变量虽然只被赋值一次,但这只局限于 static $var = xxx; 这一行代码,对于后期的赋值操作跟普通变量赋值完全一样,如 mytest3 中 $test = new Test();。
页:
[1]