PHP - 定义对象的静态数组 [英] PHP - define static array of objects
问题描述
可以初始化在PHP中的类对象的静态数组?就像你可以做
can you initialize a static array of objects in a class in PHP? Like you can do
class myclass {
public static $blah = array("test1", "test2", "test3");
}
但是当我做
class myclass {
public static $blah2 = array(
&new myotherclass(),
&new myotherclass(),
&new myotherclass()
);
}
在这里myotherclass是正确的上述MyClass的定义。
然而,这将引发一个错误;有没有办法实现呢?
where myotherclass is defined right above myclass. That throws an error however; is there a way to achieve it?
推荐答案
不。从 http://php.net/manual/en/language.oop5.static。 PHP :
像任何其他PHP静态变量,静态属性可能只
使用文字或常数初始化;前pressions是不允许的。
因此,尽管你可以一个静态属性初始化为整数或数组
(例如),你可能不会把它初始化另一个变量,一个
函数的返回值,或者一个对象。
Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.
我会初始化属性空
,使之与私人存取方法,并有访问做了真正的初始化第一次,它被称为。这里有一个例子:
I would initialize the property to null
, make it private with an accessor method, and have the accessor do the "real" initialization the first time it's called. Here's an example:
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());
这篇关于PHP - 定义对象的静态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!