开发者

PHP property as object

Is it possible to se开发者_StackOverflowt a property of a class as a object?

Like:

class User {

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

}


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());


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


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();
}


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.).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜