Inheritance in PHP allows overriding parent constructor by child class
For example:
Create parent class:
class Animal { public $name; public $health; public $alive; protected $power;//can used by childs public function __construct(string $name, int $health, int $power){ $this->name = $name; $this->health = $health; $this->power = $power; $this->alive = true; } public function calcDamage(){ return $this->power * (mt_rand(100, 300) / 200); } public function applyDamage(int $damage){ $this->health -= $damage;//analog $this->health = $this->health - $damage; if($this->health <= 0){ $this->health = 0; $this->alive = false; } } }
Now let’s create a children’s class:
class Cat extends Animal{ private $lifes;//new property //override parent constructor public function __construct(string $name, int $health, int $power){ parent::__construct($name, $health, $power);// get data from parent constructor $this->lifes = 9;//add our new properties $this->baseHealth = $health; } public function applyDamage(int $damage){ parent::applyDamage($damage); if(!$this->alive && $this->lifes > 1){ $this->lifes--; $this->alive = true; $this->health = $this->baseHealth; } } }