PHP:将类变量声明为stdClass对象

And*_*rew 16 php properties private class object

这可能很简单,但我无法弄清楚如何为Google提问,所以这里是:

所以,我经常这样做......

class foo {
    private $bar = array();
}
Run Code Online (Sandbox Code Playgroud)

...将一些类属性设置为数组.但是,我想将私有属性改为对象,如下所示:

class foo {
    private $bar = new stdClass();
}
Run Code Online (Sandbox Code Playgroud)

我尝试了几种不同的方法,但没有一种方法可行.可以这样做吗?对于奖励积分,您可以将私有财产分配为任何其他类别的对象吗?

谢谢!

pro*_*son 22

您不能在类成员声明中使用函数(包括构造函数).而是将其设置在类的构造函数中.

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);
Run Code Online (Sandbox Code Playgroud)

当你扩展类并需要覆盖构造函数但仍然需要父类构造函数中的东西时:

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);
Run Code Online (Sandbox Code Playgroud)

还应该注意这无关与物业的知名度......没关系,如果它的protected,privatepublic.