Lesson 48 of 50 – PHP Inheritance
96%

PHP Inheritance

Inheritance is an important concept in Object-Oriented Programming (OOP). It allows one class to inherit accessible properties and methods from another class. In PHP, inheritance is implemented using the extends keyword.

Inheritance helps reduce code duplication and allows you to organize related classes into a parent-child relationship.

1. What Is Inheritance?

Inheritance allows a child class to reuse accessible properties and methods defined in a parent class.

  • Parent class: The class whose features are inherited.
  • Child class: The class that extends the parent class.
  • extends: The keyword used to create the inheritance relationship.
<?php
class Animal {
    public function eat(): void {
        echo "Animal is eating.<br>";
    }
}

class Dog extends Animal {
    public function bark(): void {
        echo "Dog is barking.";
    }
}

$dog1 = new Dog();

$dog1->eat();
$dog1->bark();
?>

Output:

Animal is eating.
Dog is barking.

The Dog class inherits the eat() method from Animal and defines its own bark() method.

2. Creating a Parent and Child Class

A child class can use accessible properties and methods of its parent class while adding its own features.

<?php
class Person {
    public string $name;

    public function showName(): void {
        echo "Name: " . $this->name . "<br>";
    }
}

class Student extends Person {
    public string $course;

    public function showCourse(): void {
        echo "Course: " . $this->course;
    }
}

$student1 = new Student();

$student1->name = "Rahul";
$student1->course = "ADCA";

$student1->showName();
$student1->showCourse();
?>

Output:

Name: Rahul
Course: ADCA

The Student class inherits the name property and showName() method from Person.

It also adds its own course property and showCourse() method.

3. Types of Inheritance

Inheritance can be organized in several common patterns.

1. Single Inheritance

One child class inherits from one parent class.

<?php
class A {
    public function showA(): void {
        echo "Class A";
    }
}

class B extends A {
}

$obj = new B();
$obj->showA();
?>
2. Multilevel Inheritance

A class inherits from a child class, creating a chain.

<?php
class Grandparent {
    public function showGrandparent(): void {
        echo "Grandparent<br>";
    }
}

class ParentClass extends Grandparent {
    public function showParent(): void {
        echo "Parent<br>";
    }
}

class Child extends ParentClass {
    public function showChild(): void {
        echo "Child";
    }
}

$obj = new Child();
$obj->showGrandparent();
$obj->showParent();
$obj->showChild();
?>
3. Hierarchical Inheritance

Multiple child classes inherit from the same parent.

<?php
class Animal {
    public function eat(): void {
        echo "Eating<br>";
    }
}

class Dog extends Animal {
}

class Cat extends Animal {
}

$dog = new Dog();
$cat = new Cat();

$dog->eat();
$cat->eat();
?>

PHP supports these patterns through class inheritance. A class cannot directly extend multiple parent classes, but interfaces and traits provide other ways to share contracts and reusable functionality.

4. Method Overriding

Method overriding occurs when a child class provides its own implementation of an inherited method using a compatible method signature.

<?php
class Animal {
    public function sound(): void {
        echo "Animal makes a sound.";
    }
}

class Dog extends Animal {
    public function sound(): void {
        echo "Dog barks.";
    }
}

$animal = new Animal();
$dog = new Dog();

$animal->sound();
echo "<br>";
$dog->sound();
?>

Output:

Animal makes a sound.
Dog barks.

The Dog class overrides the inherited sound() method. Calling that method on a Dog object executes the child implementation.

This behavior is an important part of polymorphism.

5. Using the parent Keyword

The parent keyword allows a child class to call an accessible method from its parent class.

<?php
class Person {
    public function showInfo(): void {
        echo "This is a person.<br>";
    }
}

class Student extends Person {
    public function showInfo(): void {
        parent::showInfo();

        echo "This person is a student.";
    }
}

$student = new Student();
$student->showInfo();
?>

Output:

This is a person.
This person is a student.

The child method first calls the parent implementation using parent::showInfo() and then performs its own additional action.

This is useful when a child class wants to extend existing behavior instead of replacing it completely.

6. Inheritance and Constructors

If a child class declares its own constructor, PHP does not automatically call the parent's constructor. The child can call it explicitly using parent::__construct().

<?php
class Person {
    public string $name;

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

class Student extends Person {
    public string $course;

    public function __construct(
        string $name,
        string $course
    ) {
        parent::__construct($name);

        $this->course = $course;
    }

    public function showDetails(): void {
        echo "Name: " . $this->name . "<br>";
        echo "Course: " . $this->course;
    }
}

$student = new Student("Priya", "Web Development");
$student->showDetails();
?>

Output:

Name: Priya
Course: Web Development

The parent constructor initializes the name, while the child constructor initializes the course.

7. Protected Members in Inheritance

A protected property or method can be accessed within the declaring class and its subclasses. It cannot be accessed directly from outside the class hierarchy.

<?php
class Employee {
    protected float $salary = 25000;

    public function showSalary(): void {
        echo "Salary: Rs. " . $this->salary;
    }
}

class Manager extends Employee {
    public function showManagerSalary(): void {
        echo "Manager Salary: Rs. " . $this->salary;
    }
}

$manager = new Manager();

$manager->showSalary();
echo "<br>";
$manager->showManagerSalary();

// This would cause an error:
// echo $manager->salary;
?>

Output:

Salary: Rs. 25000
Manager Salary: Rs. 25000

Both methods can access the protected property, but code outside the class hierarchy cannot access it directly.

8. The final Keyword

The final keyword prevents a class from being extended or a method from being overridden.

Final Method
<?php
class Account {
    final public function showAccountType(): void {
        echo "Standard Account";
    }
}

class SavingsAccount extends Account {
    // Overriding showAccountType() is not allowed.
}

$account = new SavingsAccount();
$account->showAccountType();
?>

Output:

Standard Account
Final Class
<?php
final class Utility {
    public function showMessage(): void {
        echo "Utility class";
    }
}

// This is not allowed:
// class MyUtility extends Utility {}
?>

A final class cannot be extended. A final method cannot be overridden in a child class.

9. Practical Example: Course Management System

The following example uses inheritance to share common course information between different course types.

<?php
class Course {
    protected string $courseName;
    protected float $fee;

    public function __construct(
        string $courseName,
        float $fee
    ) {
        $this->courseName = $courseName;
        $this->fee = $fee;
    }

    public function showCourse(): void {
        echo "Course: " . $this->courseName . "<br>";
        echo "Fee: Rs. " .
            number_format($this->fee, 2) . "<br>";
    }
}

class ADCA extends Course {
    private int $durationMonths;

    public function __construct(
        float $fee,
        int $durationMonths
    ) {
        parent::__construct("ADCA", $fee);

        $this->durationMonths = $durationMonths;
    }

    public function showDetails(): void {
        $this->showCourse();

        echo "Duration: " .
            $this->durationMonths . " months";
    }
}

class WebDevelopment extends Course {
    private int $durationMonths;

    public function __construct(
        float $fee,
        int $durationMonths
    ) {
        parent::__construct("Web Development", $fee);

        $this->durationMonths = $durationMonths;
    }

    public function showDetails(): void {
        $this->showCourse();

        echo "Duration: " .
            $this->durationMonths . " months";
    }
}

$adca = new ADCA(10000, 12);
$web = new WebDevelopment(15000, 6);

echo "<h3>ADCA Course</h3>";
$adca->showDetails();

echo "<hr><h3>Web Development Course</h3>";
$web->showDetails();
?>

Output:

ADCA Course

Course: ADCA
Fee: Rs. 10,000.00
Duration: 12 months

Web Development Course

Course: Web Development
Fee: Rs. 15,000.00
Duration: 6 months

Both child classes reuse the course name and fee functionality from the parent class while maintaining their own duration and display behavior.

This pattern can help organize larger education applications with multiple course categories.


🧠 Quick Quiz

1. Which keyword is used to inherit a class in PHP?




2. Which keyword calls an accessible parent-class method?




3. What does the final keyword prevent when applied to a method?