Julio Motol
Julio Motol

Reputation: 833

PHP : instantiation of an object as a property of a class

i have the line of codes:

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

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

and the bar object contains:

class bar{
    protected $number;

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

now its throwing me Constant expression contains invalid operation

Upvotes: 1

Views: 484

Answers (1)

Calimero
Calimero

Reputation: 4308

It's not currently possible to instantiate an object during class properties declaration. That should be done in the object constructor instead :

class foo{
    public $object;

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

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

Upvotes: 9

Related Questions