代码之家  ›  专栏  ›  技术社区  ›  Andrew

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

  •  15
  • Andrew  · 技术社区  · 15 年前

    这可能很简单,但我还没有弄清楚如何表达谷歌的问题,所以这里是:

    class foo {
        private $bar = array();
    }
    

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

    class foo {
        private $bar = new stdClass();
    }
    

    我试过几种不同的方法,但都不管用。这能做到吗?为了获得加分,你能将私有财产分配给任何其他类别的对象吗?

    谢谢!

    1 回复  |  直到 15 年前
        1
  •  24
  •   random_user_name    11 年前

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

    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 ,或 public .