你能在PHP中初始化一个类中对象的静态数组吗?就像你能做到的那样
class myclass {
public static $blah = array("test1", "test2", "test3");
}
但当我这么做的时候
class myclass {
public static $blah2 = array(
&new myotherclass(),
&new myotherclass(),
&new myotherclass()
);
}
其中myotherclass定义在myclass的正上方。然而,这会抛出一个错误;有什么方法可以实现它吗?
发布于 2012-05-27 12:01:53
不是的。来自http://php.net/manual/en/language.oop5.static.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());
https://stackoverflow.com/questions/10771502
复制相似问题