您可以在 PHP 中初始化类中的静态对象数组吗?就像你能做的那样
class myclass {
public static $blah = array("test1", "test2", "test3");
}
但是当我这样做时
class myclass {
public static $blah2 = array(
&new myotherclass(),
&new myotherclass(),
&new myotherclass()
);
}
其中 myotherclass 定义在 myclass 的正上方。 但这会引发错误;有办法实现吗?
不。来自 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());
虽然您无法将其初始化为具有这些值,但您可以调用静态方法将它们推入其自己的内部集合中,就像我在下面所做的那样。这可能是您能得到的最接近的结果。
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 );
演示:http://codepad.org/InTPdUCT
这会产生以下输出:
数组 ( [0] => foo 对象 ( [栏] => 嘶嘶声 ) [1] => foo 对象 ( [栏] => 嘶嘶声 ) [2] => foo 对象 ( [栏] => 嘶嘶声 ) )
选角是你的朋友。声明为数组然后强制转换
class foo {
$object = array ("foo", "bar", "foobar");
function __construct(){
$this->object = (object) $this->object;
}
}
所谓的关联数组和对象其实没有太大区别。