use*_*950 22 php arrays object
你可以在PHP中初始化类中的静态对象数组吗?就像你能做的那样
class myclass {
public static $blah = array("test1", "test2", "test3");
}
Run Code Online (Sandbox Code Playgroud)
但是当我这样做的时候
class myclass {
public static $blah2 = array(
&new myotherclass(),
&new myotherclass(),
&new myotherclass()
);
}
Run Code Online (Sandbox Code Playgroud)
myotherclass正好在myclass之上定义.然而,这会引发错误; 有没有办法实现它?
Mar*_*eed 26
不.来自http://php.net/manual/en/language.oop5.static.php:
与任何其他PHP静态变量一样,静态属性只能使用文字或常量初始化; 表达式是不允许的.因此,虽然您可以将静态属性初始化为整数或数组(例如),但您可能不会将其初始化为另一个变量,函数返回值或对象.
我会将属性初始化为null,使用访问器方法将其设置为私有,并让访问器在第一次调用时执行"实际"初始化.这是一个例子:
class myclass {
private static $blah2 = null;
public static function blah2() {
if (self::$blah2 == null) {
self::$blah2 = array( new myotherclass(),
new myotherclass(),
new myotherclass());
}
return self::$blah2;
}
}
print_r(myclass::blah2());
Run Code Online (Sandbox Code Playgroud)