In this tutorial we will explain inheritance in PHP, a mechanism that allows a child class to inherit properties and methods from a parent class enabling code reusability. Inheritance is considered one of the four pillars of object-oriented programming.
The four pillars of object-oriented programming are:
Abstraction
Encapsulation
Inheritance
Polymorphism
A parent class is also called a superclass or base class.
A child class is also called a subclass or derived class.
Let's assume we have a class named Vehicle. A vehicle can have properties like name and color. We can define variables like $name and $color to hold the values of these properties.
Objects of a class are created using the new keyword.
In a class, variables are called properties and functions are called methods.
<?php // Parent class class Vehicle { // Properties public $name; public $color; // Methods public function __construct($name, $color) { $this->name = $name; $this->color = $color; } public function intro() { echo "The vehicle is {$this->name} and the color is {$this->color}."; } } // Child class class Yukon extends Vehicle { public function message() { echo "Am I a sedan or SUV? "; } } $yukon = new Yukon("Yukon", "black"); $yukon->message(); $yukon->intro(); ?>
The Yukon class is inherited from the Vehicle class.
The "extends" keyword is used to indicate that a class inherits from another class.
When extending a class, the child class will inherit all the public and protected methods, properties and constants from the parent class. In addition, it can have its own properties and methods.
PHP only supports single inheritance.