PHP:将对象实例化为类的属性

时间:2017-09-12 09:09:46

标签: php

我有代码行:

class foo{
    public $object = new bar(2);

    public function index(){
        dd($this->object);
    }
}

并且bar对象包含:

class bar{
    protected $number;

    function __construct($number){
        $this->number = $number;
    }
}

现在它抛出了我Constant expression contains invalid operation

1 个答案:

答案 0 :(得分:8)

目前无法在类属性声明期间实例化对象。这应该在对象构造函数中完成:

class foo{
    public $object;

    public function __construct() {
        $this->object = new bar(2);
    }

    public function index(){
        dd($this->object);
    }
}