PHP - 定义对象的静态数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10771502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP - define static array of objects
提问by user1181950
can you initialize a static array of objects in a class in PHP? Like you can do
你能在 PHP 的类中初始化一个静态对象数组吗?就像你可以做的
class myclass {
public static $blah = array("test1", "test2", "test3");
}
but when I do
但是当我这样做的时候
class myclass {
public static $blah2 = array(
&new myotherclass(),
&new myotherclass(),
&new myotherclass()
);
}
where myotherclass is defined right above myclass. That throws an error however; is there a way to achieve it?
其中 myotherclass 定义在 myclass 正上方。但是,这会引发错误;有没有办法实现它?
回答by Mark Reed
Nope. From http://php.net/manual/en/language.oop5.static.php:
不。来自http://php.net/manual/en/language.oop5.static.php:
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.
像任何其他 PHP 静态变量一样,静态属性只能使用文字或常量进行初始化;不允许使用表达式。因此,虽然您可以将静态属性初始化为整数或数组(例如),但您不能将其初始化为另一个变量、函数返回值或对象。
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:
我会将属性初始化为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());
回答by Sampson
While you cannot initialize it to have these values, you can call a static method to push them into its own internal collection, as I've done below. This may be as close as you'll get.
虽然您无法将其初始化为具有这些值,但您可以调用静态方法将它们推送到其自己的内部集合中,就像我在下面所做的那样。这可能与您会得到的一样接近。
class foo {
public $bar = "fizzbuzz";
}
class myClass {
static public $array = array();
static public function init() {
while ( count( self::$array ) < 3 )
array_push( self::$array, new foo() );
}
}
myClass::init();
print_r( myClass::$array );
Demo: http://codepad.org/InTPdUCT
演示:http: //codepad.org/InTPdUCT
Which results in the following output:
这导致以下输出:
Array
(
[0] => foo Object
(
[bar] => fizzbuzz
)
[1] => foo Object
(
[bar] => fizzbuzz
)
[2] => foo Object
(
[bar] => fizzbuzz
)
)

