See this scenario :
class Parent { protected $property1; // Not set protected $property2 = '2'; // Set to 2 public function __construct(){ $this->property1 = '1'; // Set to 1 } } // class Parent; class Child extends Parent { public function __construct(){ // Child CHOOSES to call parent constructor parent::__construct(); // optional call (what if skipped) // but if he does not, ->property1 remains unset! } } // class Child;
This is the difference between the two challenges. parent :: __ construct () is optional for child classes that inherit from the parent. So:
- if you have a scalar (as in
is_scalar() ) properties that need to be pre-configured, do this in the class definition that they exist in child classes as well. - If you are properties that depend on arguments or are optional , put them in the constructor .
It all depends on how you create your code functionality.
There is no right, this is just what suits you.
source share