PHP Inheritance


Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a class to inherit properties and methods from another class. In PHP, inheritance promotes code reusability, reduces redundancy, and enables hierarchical relationships between classes.

Understanding inheritance is essential for designing scalable applications and implementing complex behaviors efficiently.

What is Inheritance?

Inheritance allows one class (called the child or subclass) to acquire the properties and methods of another class (called the parent or superclass).

Key points about inheritance:

  • The child class inherits all non-private properties and methods of the parent class.

  • The child class can add new properties or methods or override existing ones.

  • PHP uses the keyword extends to indicate inheritance.

Basic Example of Inheritance

class Vehicle {
    public $brand;

    public function start() {
        echo $this->brand . " vehicle started.<br>";
    }
}

class Car extends Vehicle {
    public function honk() {
        echo $this->brand . " car honks.<br>";
    }
}

$car = new Car();
$car->brand = "Toyota";
$car->start(); // Outputs: Toyota vehicle started.
$car->honk();  // Outputs: Toyota car honks.

Here, the Car class inherits the brand property and start() method from the Vehicle class while adding its own method honk().

Access Modifiers in Inheritance

Inheritance respects access modifiers:

  • Public properties/methods are accessible in the child class.

  • Protected properties/methods are accessible in the child class.

  • Private properties/methods are not accessible in the child class.

Example:

class ParentClass {
    public $publicProp = "Public";
    protected $protectedProp = "Protected";
    private $privateProp = "Private";

    public function showProps() {
        echo $this->publicProp . ", " . $this->protectedProp . "<br>";
        // echo $this->privateProp; // Not accessible here
    }
}

class ChildClass extends ParentClass {
    public function accessProps() {
        echo $this->publicProp . ", " . $this->protectedProp . "<br>";
        // echo $this->privateProp; // Error: Cannot access private property
    }
}

$child = new ChildClass();
$child->accessProps(); // Outputs: Public, Protected

This shows that private members cannot be inherited, while public and protected members can.

Overriding Methods

Child classes can override parent methods to change or extend behavior:

class Vehicle {
    public function start() {
        echo "Vehicle started.<br>";
    }
}

class Bike extends Vehicle {
    public function start() {
        echo "Bike started with a kick.<br>";
    }
}

$bike = new Bike();
$bike->start(); // Outputs: Bike started with a kick.

To call the parent method inside the overridden method, use parent::methodName():

class Bike extends Vehicle {
    public function start() {
        parent::start(); // Calls Vehicle start
        echo "Bike also checked safety.<br>";
    }
}

$bike = new Bike();
$bike->start();

Output:

Vehicle started.
Bike also checked safety.

Constructors and Inheritance

When a parent class has a constructor, the child class does not automatically call it. You must explicitly call parent::__construct() in the child constructor.

Example:

class Vehicle {
    public $brand;

    public function __construct($brand) {
        $this->brand = $brand;
    }
}

class Car extends Vehicle {
    public $color;

    public function __construct($brand, $color) {
        parent::__construct($brand);
        $this->color = $color;
    }

    public function display() {
        echo "Car: " . $this->brand . " | Color: " . $this->color . "<br>";
    }
}

$car = new Car("Honda", "Blue");
$car->display(); // Outputs: Car: Honda | Color: Blue

Multiple Levels of Inheritance

PHP supports multi-level inheritance, where a class can inherit from a child, forming a hierarchy.

class Vehicle {
    public $brand;
}

class Car extends Vehicle {
    public $model;
}

class SportsCar extends Car {
    public $topSpeed;

    public function display() {
        echo $this->brand . ", " . $this->model . ", " . $this->topSpeed . "<br>";
    }
}

$sportCar = new SportsCar();
$sportCar->brand = "Ferrari";
$sportCar->model = "F8";
$sportCar->topSpeed = "340 km/h";
$sportCar->display(); // Outputs: Ferrari, F8, 340 km/h

Best Practices for Inheritance

  1. Use inheritance only when there is a clear “is-a” relationship. For example, a Car is a Vehicle.

  2. Avoid deep inheritance hierarchies; prefer composition if needed.

  3. Always call parent::__construct() when necessary.

  4. Keep overridden methods focused; don’t replicate parent logic unnecessarily.

  5. Use protected properties/methods for values meant for child classes.

Common Mistakes

  • Accessing private parent properties in a child class.

  • Forgetting to call parent constructors.

  • Overusing inheritance, leading to complex hierarchies.

  • Not overriding methods properly, causing unexpected behavior.

Summary of the Tutorial

  • Inheritance allows a child class to inherit properties and methods from a parent class.

  • Public and protected members are inherited; private members are not.

  • Child classes can override methods and call parent methods using parent::.

  • Constructors in parent classes must be called explicitly from child classes.

  • Multi-level inheritance allows creating hierarchies but should be used carefully.

Mastering inheritance is crucial for building reusable and organized PHP applications while minimizing redundant code.


Practice Questions

  1. Create a parent class Vehicle with a property brand and method start(). Create a child class Car that inherits from Vehicle and adds a method honk(). Instantiate Car and call both methods.

  2. Write a PHP program with a parent class Employee containing a protected property salary. Create a child class Manager that sets and displays the salary.

  3. Create a class Animal with a method makeSound(). Create subclasses Dog and Cat that override makeSound() to print their respective sounds. Instantiate objects and call the method for each.

  4. Create a parent class Vehicle with a constructor that accepts brand. Create a child class Bike with a constructor that also accepts type and calls the parent constructor. Display both properties.

  5. Create a class Person with private properties name and age and public getter/setter methods. Create a subclass Student and use the inherited getters/setters to set and display values.

  6. Write a PHP program with multi-level inheritance: class Vehicle, subclass Car, and subclass SportsCar. Add properties and methods in each and display all values for a SportsCar object.

  7. Create a class Shape with a method area(). Create subclasses Rectangle and Square that override the area() method. Instantiate objects and calculate areas.

  8. Create a parent class ParentClass with a protected method showMessage(). Create a child class ChildClass that calls this method from within its own method.

  9. Create a class BankAccount with a constructor to initialize accountNumber and balance. Create a subclass SavingsAccount with an additional property interestRate. Instantiate the subclass and display all details.

  10. Write a PHP program with a class ParentClass having a destructor. Create a subclass ChildClass with its own destructor and call parent::__destruct() inside it. Observe the order of destructor execution.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top