PHP property as object

三世轮回 提交于 2019-12-30 07:31:30

问题


Is it possible to set a property of a class as a object?

Like:

class User {

    public $x = "";
    public $y = new ErrorVO();
    public $w = new array();

}

回答1:


In the constructor, yes.

class User
{
    public $x = "";
    public $y = null;
    public $w = array();

    public function __construct()
    {
        $this->y = new ErrorVO();
    }
}

Edit

KingCrunch made a good point: You should not hard-code your dependencies. You should inject them to your objects (Inversion of Control (IoC)).

class User
{
    public $x = "";
    public $y = null;
    public $w = array();

    public function __construct(ErrorVO $y)
    {
        $this->y = $y;
    }
}

new User(new ErrorVD());



回答2:


Just my preferred solution, even if the others already explain everything: Injection

class A {
  public $a;
  public function __construct (ErrorVO $a) {
    $this->a = $a;
  }
}

This keeps the class testable and allows to replace the wanted ErrorVO-implementation very easy. Of course you can combine both solutions into one

class A {
  public $a;
  public function __construct (ErrorVO $a = null) {
    $this->a = is_null($a) ? new ErrorVO : $a;
  }
}

Minor Update: In the meantime you can write the second example like this

class A {
  public $a;
  public function __construct (ErrorVO $a = null) {
    $this->a = $a ?: new ErrorVO;
  }
}

It's slightly more compact and imo it makes the intention more clear. Compare the ?:-operator with MySQLs COALESCE




回答3:


You cannot declare them in the property declarations, but you can instantiate them in the constructor __construct() The array() can be instantiated in the public $w without the new keyword: public $w = array();

public function __construct()
{
  $this->y = new ErrorVO();
}



回答4:


Yes, it is. But this can be done during the class instantiation (in the constructor) or later, for example:

  • during instantiation:

    class A {
        public $a;
        public function __construct() {
            $this->$a = (object)array(
                'property' => 'test',
            );
        }
    }
    
    $my_object = new A();
    echo $my_object->a->property; // should show 'test'
    
  • after instantiation:

    class B {
        public $b;
    }
    
    $my_object = new B();
    $my_object->b = (object)array(
        'property' => 'test',
    );
    echo $my_object->b->property; // should also show 'test'
    

You can not assign object directly in class definition outside constructor or other methods, because you can do it only with scalars (eg. integers, strings etc.).



来源:https://stackoverflow.com/questions/5984360/php-property-as-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!