Overriding parent constructor by child class. PHP example open

Overriding parent constructor by child class. PHP example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: PHP 7

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;
		}
	}
}
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation