PHP Inheritance

by Vincy. Last modified on July 3rd, 2022.

Inheritance is one of the popularly used Object Oriented Programming features. It allows having shared properties and functions between related classes. This feature allows us to interrelate classes, to abstract data and methods and increase reusability.

One of the noticeable changes while migrating from PHP version 4 to PHP version 5 is of introducing the Object-oriented Programming feature as we have seen in Growth of PHP. Among the limited set of OOPS features supported by PHP, inheritance is an attractive concept by providing the above functionalities listed.

Before getting into PHP inheritance, let us refresh the idea about inheritance and its types in general. As per this principle, a class can be derived from another class, whereas the class derived is called as child or subclass and the other is called as parent or superclass.

The superclass has its own properties and functions which can be derived from the subclass and added to that, the subclass can have its own properties.

Now the advantages of inheritance are that there is no need to redefine the required properties of super class one again in subclass since they could be inherited. That is what, we have said that inheritance increases reusability and reduces lines of code and thereby it increases simplicity among interrelated classes.

Types of PHP Inheritance

Generally, inheritance has three types, single, multiple and multi-level inheritance. But, PHP supports single inheritance and multi-level inheritance. That means the subclass will be derived from a parent class. Even though PHP is not supporting any multiple inheritances, we can simulate it by using PHP interfaces.

In PHP, inheritance can be done by using extends keyword, meaning that, we are extending the derived class with some additional properties and methods of its parent class. The syntax for inheriting a class is as follows.

Child_class_name extends Parent_class_name {
...
}

Note: We can inherit parent class properties and functions if and only if they have public or protected access modifiers.

PHP Single Inheritance

For implementing the single inheritance concept in PHP, we require two classes one as a parent and the other as a child. Let us have two such classes named Toys and SoftToys, respectively as shown below.

Class Toys:

<?php

class Toys
{

    public $categories = array(
        "puzzles",
        "pull back",
        "remote",
        "soft"
    );

    public $toys = array(
        array(
            "name" => "Mechanical Cars",
            "category" => "pull back"
        ),
        array(
            "name" => "Jigsaw",
            "category" => "puzzles"
        ),
        array(
            "name" => "HiTech Cars",
            "category" => "remote"
        ),
        array(
            "name" => "Teddy Bears",
            "category" => "soft"
        ),
        array(
            "name" => "Baby pillow",
            "category" => "soft"
        ),
        array(
            "name" => "Chinese Checker",
            "category" => "puzzles"
        ),
        array(
            "name" => "Jumbo Helicopter",
            "category" => "remote"
        )
    );

    function getToys()
    {
        for ($i = 0; $i < count($this->toys); $i ++) {
            $toys_list[] = $this->toys[$i]["name"];
        }
        return $toys_list;
    }

    function getToysByCategory($category)
    {
        for ($i = 0; $i < count($this->toys); $i ++) {
            if ($this->toys[$i]["category"] == $category)
                $toys_list[] = $this->toys[$i]["name"];
        }
        return $toys_list;
    }
}
?>

This class includes properties like a list of categories in an array and also has entire toy information in an associative array. After that, getToys() is used to get all toys, whereas, getToysByCategory() returns a list of toys by its category passing as an argument.

Class SoftToys:

<?php

class SoftToys extends Toys
{

    protected $category = "soft";

    function getToys()
    {
        return $this->getToysByCategory($this->category);
    }
}
?>

This class is derived from the Toys class and overrides its getToys() method to return only the list of soft toys.

After defining two classes, now, is the time to access their properties and functions through the instance of these classes, to see the effect of inheritance. For that, class instances are created as follows, outside the class definition.

<?php
$objToys = new Toys();
$objSoftToys = new SoftToys();
?>

And the properties and functions are accessed by using the following code.

<?php
print "<pre>";
print_r($objToys->categories);
print_r($objSoftToys->categories);
print_r($objToys->getToys());
print_r($objSoftToys->getToys());
print "</pre>";
?>

Since SoftToys class is derived from Toys class, accessing categories property using either class instance will print the same array of results as,

Array
(
    [0] => puzzles
    [1] => pull back
    [2] => remote
    [3] => soft
)

But, getToys() function is overriding in child class. So, accessing this method by using the Toys or SoftToys class instance will print a different set of toys list to the browser as shown below.

Array
(
    [0] => Mechanical Cars
    [1] => Jigsaw
    [2] => HiTech Cars
    [3] => Teddy Bears
    [4] => Baby pillow
    [5] => Chinese Checker
    [6] => Jumbo Helicopter
)
Array
(
    [0] => Teddy Bears
    [1] => Baby pillow
)

Leave a Reply

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

↑ Back to Top

Share this page