Inheritance in PHP: Share Code from Class to Class & Examples

inheritance in php

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.

We will cover the following topics in this article:

  • Understanding how inheritance works and its definition
  • Types of inheritance
  • Using the final keyword 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 Box class has a method capacity() that outputs “Some capacity”.
  • The Carton class inherits from Box. It uses the extends keyword.
  • It inherits from Box since Carton does not have its own capacity() method.
  • A Carton object 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 extends keyword 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 Triangle class replaces the area() method with its own version.
  • The parent::area() call inside Triangle runs the area() method from the Shape class.
  • After that, the Triangle class 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:

  1. Define the parent class: This class contains common properties and methods.
  2. Create the child class: Use the extends keyword to inherit from the parent class.
  3. 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 extends keyword 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 final keyword 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?

Use the extends keyword to define a child class that inherits from a parent class.

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?

Yes, a child class can override methods inherited from a parent class by defining a method with the same name.
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?

Use the parent:: keyword to call a parent class method from within a 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?

No, private properties and methods are not accessible to child classes. However, protected and public properties and methods are inherited.

What is the final keyword in PHP, and how does it relate to inheritance?

The final keyword prevents a class from being extended or a method from being overridden.
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?

No, PHP does not support multiple inheritance directly. However, PHP offers traits to achieve similar functionality, allowing methods to be shared across multiple classes without creating a strict parent-child relationship.

Similar Reads

History of PHP: From PHP/FI to Modern Web Development

You use PHP every day if you build websites, but most people do not know where it came from or…

PHP array_count_values: How it Works with Examples

Developers use the array_count_values function in PHP to find how many times each value appears in an array. What is…

Concatenating Strings in PHP: Tips and Examples

In PHP, string operators, such as the concatenation operator (.) and its assignment variant (.=), are employed for manipulating and…

PHP strpos Function: How it Works with Examples

Sometimes the string you expect is there, but strpos function gives a surprise in PHP. It may show the result…

PHP Namespace: How to Group Code (With Example)

PHP namespace solves the problem of name conflicts. Different developers may create functions-classes, or constants with the same name. PHP…

PHP array_fill_keys: Create Arrays with Specific Keys

The PHP array_fill_keys function helps you to build an array where each key has the same value. What is the…

OOP Interface PHP: How to Set Rules for Classes

PHP developers relied on class inheritance to share functionality before the OOP interface, but this approach had limits. It solves…

PHP $_POST: Handling Form Data in PHP

The term $_POST is quite familiar territory when one works with forms in PHP. This tutorial talks about what $_POST does, how to use…

PHP trim(): How to remove Whitespace from String

Early PHP scripts often failed because of extra spaces or line breaks in strings. These issues came from user input…

PHP sizeof: How to Count Elements in Arrays with Examples

The sizeof function in PHP exists to help developers know how many items an array holds. Understand the sizeof Function…

Previous Article

Constants in PHP: How They Work & Examples

Next Article

PHP OOP Programming: A Complete Tutorial

Write a Comment

Leave a Comment

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


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.