PHP
Inheritance chain
Learn to build a multi-level inheritance chain and propagate behavior.
Multi-level inheritance chain
Inheritance is not limited to one level. A child class can itself be the parent of another class. This creates a three-or-more level inheritance chain.
For example, Vehicle, Car and ElectricCar form a three-level chain. ElectricCar inherits from Car, which inherits from Vehicle. Each level adds a new capability.
This structure is ideal for modeling real-world classifications: a Tesla is a vehicle, a car, and an electric vehicle at the same time.
Transitive inheritance
A key feature of an inheritance chain is that it is transitive. If A inherits from B, and B from C, then A automatically inherits from C too.
So an ElectricCar instance can directly call Vehicle's methods, skipping the middle Car level. PHP looks up methods upwards in the class hierarchy.
When designing classes, each link of the chain must be meaningful: each level should add a real extension to the previous one.
Exercise Build the Vehicle → Car → ElectricCar chain
In this lesson Vehicle's info() method returns just brand. You will derive Car from Vehicle and ElectricCar from Car. The Car::drive() method should call $this->info() and append " is driving". The ElectricCar::charge() method should call $this->drive() and append ", charging". Create a Tesla ElectricCar instance and print the charge() output.
Show example solution
Car extends Vehicle, ElectricCar extends Car. The drive() method calls $this->info(); the charge() method calls $this->drive().
Example solution:
<?php
class Vehicle {
public string $brand;
public function __construct(string $brand) {
$this->brand = $brand;
}
public function info(): string {
return $this->brand;
}
}
class Car extends Vehicle {
public function drive(): string {
return $this->info() . " is driving";
}
}
class ElectricCar extends Car {
public function charge(): string {
return $this->drive() . ", charging";
}
}
$tesla = new ElectricCar("Tesla");
echo $tesla->charge();
Test yourself
-
In the Vehicle → Car → ElectricCar chain, can ElectricCar call a method of Vehicle?
- Yes, inheritance is transitive
- No, only the direct parent's methods
- Only its own defined methods
- Only protected methods
Show answer
Yes, inheritance is transitive — Correct; inheritance is transitive. ElectricCar can use Vehicle's public/protected methods.
-
Complete the inheritance chain
class Car ____ Vehicle {
// ...
}
class ElectricCar extends Car {
// ...
}
Show answer
class Car extends Vehicle {
// ...
}
class ElectricCar extends Car {
// ...
}
-
Match inheritance chain concepts
- Inheritance chain
- Multi-level inheritance
- Transitive
- A->B->C implies A->C
- Vehicle/Car/ElectricCar
- Three-level example
- Chain design
- Each level adds value
Next lesson: Summary - Inheritance