Can't override parent construct

Can't override parent construct
php
Ethan Jackson

I'm trying to override parent construct class in child class by following way but it's not success !

Parent class:

class Base extends \Core\Model { /** * Error messages * * @var array */ public $errors = []; public $errorMsg = ''; /** * Class constructor * * @param array $data initial property values * * @return void */ public function __construct($data = []) { foreach ($data as $key => $value) { $this->$key = $value; }; } }

Child class :

class Visit extends Base { /** * Error messages * * @var array */ public $subscribe; /** * Class constructor * * @param array $data initial property values * * @return void */ public function __construct() { parent::__construct($data = []); $this->subscribe = new Subscribe(); } }

Please note above code it's not my full code ( too long ), I've just copy construct to avoid misunderstanding.

The data comes from a form in controller ($_POST), so when I run the above I got the following:

Message: 'Undefined property: App\Models\Visit::$phone'

Which mean parent construct didn't work after overriding !

Hope it's clear and thanks in advance.

Answer

The calling side tries to construct object from your class with array of arguments and suppose that they will become a public properties of this object as it is done in Base constructor.

If it is done like this $a=new Base(['phone'=>'123']) then $a->phone will be available.

But your constructor does not use any arguments, while it should forward them to parent.
Try this way:

public function __construct($data=[]) { parent::__construct($data); $this->subscribe = new Subscribe(); }

Related Articles