PHP Inheritance
Inheritance lets a class take the members of another class and add its own. The first class is the parent, and the class built on it is the child.
A child uses a parent method
Car extends Vehicle and adds nothing. The describe call still works because the method comes from the parent.
<?php
class Vehicle {
public function describe() {
echo "A vehicle\n";
}
}
class Car extends Vehicle {
}
$car = new Car();
$car->describe();A child adds its own method
parent::describe() runs the parent version first. The child then adds its own line and a honk method of its own.
<?php
class Vehicle {
public function describe() {
echo "A vehicle\n";
}
}
class Car extends Vehicle {
public function describe() {
parent::describe();
echo "It is a car\n";
}
public function honk() {
echo "Beep\n";
}
}
$car = new Car();
$car->describe();
$car->honk();A protected property in the child
The brand property in Vehicle is protected. Protected means the class and its children can reach it, and the child method reads it here.
<?php
class Vehicle {
protected $brand = "";
public function setBrand($brand) {
$this->brand = $brand;
}
}
class Car extends Vehicle {
public function showBrand() {
echo "Brand: " . $this->brand . "\n";
}
}
$car = new Car();
$car->setBrand("Ford");
$car->showBrand();Example
<?php
class Vehicle {
protected $brand = "";
public function setBrand($brand) {
$this->brand = $brand;
}
public function describe() {
echo "Brand: " . $this->brand . "\n";
}
}
class Car extends Vehicle {
public function wheels() {
echo "Wheels: 4\n";
}
}
$car = new Car();
$car->setBrand("Ford");
$car->describe();
$car->wheels();Key points
- The word extends makes one class the child of another.
- The child gets the public members of the parent.
- The child gets the protected members of the parent.
- The child can add methods that the parent does not have.
- parent:: calls the parent version of a method.
In this example, Car extends Vehicle and gains its brand handling. setBrand stores the brand, and describe prints it from the parent. The wheels method belongs to Car alone and prints the second line.
Note
One class extends exactly one parent in PHP.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz PHP Compiler
Exercise
Which line makes Car the child of Vehicle?