这可能非常简单,但我一直无法弄清楚如何为 Google 解决这个问题,所以这里是:
所以,我经常做这样的事情......
class foo {
private $bar = array();
}
... 将某些类属性设置为数组。但是,我想将私有(private)属性改为对象,如下所示:
class foo {
private $bar = new stdClass();
}
我尝试了几种变体,但都没有用。这可以做到吗?对于奖励积分,您可以将私有(private)属性(property)指定为任何其他类别的对象吗?
谢谢!
最佳答案
您不能在类成员声明中使用函数(包括构造函数)。而是在类的构造函数中设置它。
class Foo {
private $bar;
private $baz;
public function __construct() {
$this->bar = new stdClass();
$this->baz = new Bat();
}
public function __get($key) {
if(isset($this->$key) {
return $this->$key;
}
throw new Exception(sprintf('%s::%s cannot be accessed.', __CLASS__, $key));
}
}
$foo = new Foo();
var_dump($foo->bar);
var_dump($foo->bat);
当你扩展类并需要覆盖构造函数但仍然想要父类构造函数中的东西时:
class FooExtended
{
protected $coolBeans;
public function __construct() {
parent::__construct(); // calls the parents constructor
$this->coolBeans = new stdClass();
}
}
$foo = new FooExtended();
var_dump($foo->bar);
var_dump($foo->bat);
var_dump($foo->coolBeans);
还应注意,这与属性的可见性无关...它是 protected
、private
还是 都无关紧要公开
。
关于PHP:将类变量声明为 stdClass 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3818855/