PHP developers copied and pasted code across multiple files before inheritance came, which made updates difficult. They updated functions in every file manually if they needed changes. This led to errors, duplication, and wasted time.
Table of Content
We will cover the following topics in this article:
- Understanding how inheritance works and its definition
- Types of inheritance
- Using the
finalkeyword with inheritance - Common issues with inheritance and their solutions
- Examples
Let’s start with the definition.
Understand What Inheritance Is in PHP?
Inheritance is a feature in PHP that allows a class to reuse code from another class. A child class gains properties and methods from a parent class. This reduces code duplication and improves maintainability.
Here are reasons to use inheritance in PHP:
- Inheritance lets a child class reuse code from a parent class. It saves time and effort.
- It can be made in the parent class when a change is needed and the child classes automatically get the update.
- It helps structure code and group common functionality in one place.
- Inheritance prevents the repetition of the same code in multiple classes.
- A child class can add new features or override methods from the parent class to suit its needs.
- Developers work on different parts of a project without duplication of effort.
For example:
class Box {
public function capacity() {
echo "Some capacity";
}
}
// => The carton inherits box when use extends keyword
class Carton extends Box {
}
$carton = new Carton();
$carton->capacity(); Output:
Some capacity
How it works:
- The
Boxclass has a methodcapacity()that outputs “Some capacity”. - The
Cartonclass inherits fromBox. It uses theextendskeyword. - It inherits from
BoxsinceCartondoes not have its owncapacity()method. - A
Cartonobject is created, and calling$carton->capacity();prints “Some capacity”.
Hence, you can override the function of the parent class. Here is an example:
class Box {
public function capacity() {
echo "Some capacity";
}
}
class Carton extends Box {
// Override the capacity method
public function capacity() {
echo "Carton capacity";
}
}
$carton = new Carton();
$carton->capacity();Output:
Carton capacity
The Carton class overrides the capacity() method from the Box class. It outputs “Carton capacity” instead of “Some capacity” when you call $carton->capacity();.
Here are the key points:
- The
extendskeyword lets a class inherit from another. - A child class can override methods from the parent.
- The child class can add new methods or properties.
- The protected and public properties/methods are inherited. Private ones are not.
You will learn how to use parent keyword to access the parent class methods in the following section.
Using parent:: to Call Parent Methods
You can use parent:: to call a parent class method from a child class. This is useful when you want to reuse the parent class method as you add extra functionality in the child class.
For example:
class Shape {
public function area() {
echo "Shape area";
}
}
class Triangle extends Shape {
public function area() {
// Call the parent class method
parent::area();
echo " - Triangle area";
}
}
$triangle = new Triangle();
$triangle->area();Here is the output:
Shape area - Triangle area
- The
Triangleclass replaces thearea()method with its own version. - The
parent::area()call insideTriangleruns thearea()method from theShapeclass. - After that, the
Triangleclass adds its own message.
So, how to create a parent and child class in PHP? Let’s answer this question in the following section.
Create a Parent and Child Class in PHP
Follow these steps to create a parent and child class in PHP:
- Define the parent class: This class contains common properties and methods.
- Create the child class: Use the
extendskeyword to inherit from the parent class. - Use methods from the parent class: The child class can use the inherited methods or override them.
Here is an example:
// Parent class
class Material {
public function type() {
echo "General material";
}
}
// Child class inherits Material
class Wooden extends Material {
public function property() {
echo "Made of wood";
}
}
// Create an object of the child class
$wooden = new Wooden();
$wooden->type();
$wooden->property(); Output:
General material
Made of wood
The child class can call both its own methods and those inherited from the parent.
Anyway, let’s move on to the following section to take a look at the types of inheritance in PHP.
Types of Inheritance in PHP
PHP does not allow a class to inherit from multiple parent classes. Instead, PHP uses traits to achieve similar functionality.
PHP supports different types of inheritance:
- Single inheritance.
- Multilevel inheritance.
- Hierarchical inheritance.
Let’s take each one in-depth.
Single Inheritance
Single inheritance refers to a class inherits only one parent class. This allows the child class to access the properties and methods of the parent class.
For example:
class Animal {
public function sound() {
echo "Some sound";
}
}
class Cat extends Animal {
public function sound() {
echo "Meows";
}
}
$cat= new Cat();
$cat->sound(); Output:
Meows
Multilevel Inheritance
Multilevel inheritance occurs when a class inherits from a class that is also a child of another class. This creates a chain of inheritance, where each class inherits from the one before it.
For example:
// Grandparent class
class Animal {
public function sound() {
echo "Some sound";
}
}
// Parent class inherits from Animal
class Mammal extends Animal {
public function walk() {
echo "Mammal walking";
}
}
// Child class inherits from Mammal
class Dog extends Mammal {
public function bark() {
echo "Bark";
}
}
$dog = new Dog();
$dog->sound();
echo "\n";
$dog->walk();
echo "\n";
$dog->bark(); Here is output:
Some sound
Mammal walking
Bark
Hierarchical Inheritance
Hierarchical inheritance happens when a single parent class is inherited by multiple child classes.
Each child class gets access to the properties and methods of the parent class, but can have its own unique features.
Example:
// Parent class
class Animal {
public function sound() {
echo "Some sound";
}
}
// Child class 1 inherits from Animal
class Dog extends Animal {
public function bark() {
echo "Bark";
}
}
// Child class 2 inherits from Animal
class Cat extends Animal {
public function meow() {
echo "Meow";
}
}
$dog = new Dog();
$dog->sound();
echo "\n";
$dog->bark();
echo "\n";
$cat = new Cat();
$cat->sound();
echo "\n";
$cat->meow();
echo "\n";Here is output:
Some sound
Bark
Some sound
Meow
In the following section, you will learn how to lock a class and prevent inheritance and overriding.
Use final Keyword to Prevent Overriding and Inheritance
The final keyword can be used to prevent a class from being inherited or a method from being overridden.
Here is the syntax of the final class:
final class Ball {
// Methods and Attirbutes
}Here is syntax of final method:
class Football{
final public function player() {
/* Function Body */
}
}That does:
- Prevent classes from being extended by any other class.
- Prevent methods or functions from being overridden in any child.
Here is an example:
final class Light {
public function color() {
echo "White";
}
}
class LED extends Light { // <== Error
public function color() {
echo "Blue";
}
}This will cause an error because the class is final and cannot be inherited. Here is the result:
PHP Fatal error: Class LED cannot extend final class Light in /lights.php on line 7
Here is another example for the final method:
class Technology {
// Final method
final public function type() {
echo "Device type";
}
}
class Laptop extends Technology {
public function type() { // <== Error
echo "Laptop";
}
}This will cause an error because the method is final and cannot be overridden.
Here is the output:
PHP Fatal error: Cannot override final method Technology::type() in /tech.php on line 9
Wrapping Up
You learned how to use inheritance in PHP and what it is. Here is a quick recap:
- Inheritance allows child classes to reuse code from parent classes.
- The
extendskeyword allows a class to inherit from a parent class. - You can override parent class methods in the child class.
- The
parent::keyword lets a child class call a parent class method. - PHP supports inheritance types such as single, multilevel, and hierarchical inheritance.
- The
finalkeyword prevents classes from being inherited and methods from being overridden.
How do I create a child class that inherits from a parent class in PHP?
class ParentClass {
public function sayHello() {
echo "Hello from Parent!";
}
}
class ChildClass extends ParentClass {
// Additional methods or properties
}
$child = new ChildClass();
$child->sayHello(); // Outputs: Hello from Parent!
Can a child class override a method from a parent class?
class ParentClass {
public function sayHello() {
echo "Hello from Parent!";
}
}
class ChildClass extends ParentClass {
public function sayHello() {
echo "Hello from Child!";
}
}
$child = new ChildClass();
$child->sayHello(); // Outputs: Hello from Child!
/pre>How can you call the parent class's method in the child class?
class ParentClass {
public function sayHello() {
echo "Hello from Parent!";
}
}
class ChildClass extends ParentClass {
public function sayHello() {
parent::sayHello(); // Call the parent method
echo " Hello from Child!";
}
}
$child = new ChildClass();
$child->sayHello(); // Outputs: Hello from Parent! Hello from Child!
/pre>Can a child class inherit private properties or methods from a parent class?
What is the final keyword in PHP, and how does it relate to inheritance?
final class Light {
public function color() {
echo "White";
}
}
class LED extends Light { // Error: Cannot extend a final class
public function color() {
echo "Blue";
}
}
/pre>Does PHP support multiple inheritance?
Similar Reads
You may need to get part of a text when you work with text in PHP. The mb_substr gives you…
If you are working with PHP and need a way to confirm if something is indeed a file, the is_file function will…
When working with big arrays in PHP, things can get messy. That is where php array_chunk() steps in by providing…
PHP-type hinting is something that keeps your code in check and helps your functions receive just the right types of…
PHP and MySQL have become an inseparable pair for web developers. One handles the logic, while the other stores the…
PHP array_intersect_uassoc checks two or more arrays and returns matches. It compares both the values and the keys with a…
Sometimes, when you run a script, you may encounter an error because the directory you're trying to access doesn't exist.…
Think about the PHP variable as little storage boxes holding your data, whether it is a number, a word, or…
In some cases, you need to handle a lot of data or simply try to open a file, or read…
The array_combine function in PHP creates a new array with one array for keys and another for values. It needs…