0
0
PHPprogramming~5 mins

Why inheritance is needed in PHP

Choose your learning style9 modes available
Introduction

Inheritance helps us reuse code and organize related things easily. It lets one class get features from another without rewriting them.

When you have many objects that share common features but also have their own special parts.
When you want to avoid repeating the same code in multiple places.
When you want to create a clear family-like relationship between classes.
When you want to add new features to an existing class without changing it.
When you want to make your code easier to maintain and understand.
Syntax
PHP
<?php
class ParentClass {
    // common properties and methods
}

class ChildClass extends ParentClass {
    // additional properties and methods
}
?>
The extends keyword is used to inherit from a parent class.
The child class gets all public and protected properties and methods from the parent.
Examples
This example shows a Dog class inheriting from Animal. Dog can eat (from Animal) and bark (its own method).
PHP
<?php
class Animal {
    public function eat() {
        echo "Eating food\n";
    }
}

class Dog extends Animal {
    public function bark() {
        echo "Barking\n";
    }
}

$dog = new Dog();
$dog->eat();
$dog->bark();
?>
Car inherits start() from Vehicle and adds honk() of its own.
PHP
<?php
class Vehicle {
    public function start() {
        echo "Starting vehicle\n";
    }
}

class Car extends Vehicle {
    public function honk() {
        echo "Honking horn\n";
    }
}

$car = new Car();
$car->start();
$car->honk();
?>
Sample Program

This program shows a Student class inheriting greet() from Person and adding study(). It prints greetings and study message.

PHP
<?php
class Person {
    public function greet() {
        echo "Hello!\n";
    }
}

class Student extends Person {
    public function study() {
        echo "Studying hard\n";
    }
}

$student = new Student();
$student->greet();
$student->study();
?>
OutputSuccess
Important Notes

Inheritance helps keep code DRY (Don't Repeat Yourself).

Only public and protected members are inherited, private ones are not.

Use inheritance to model "is-a" relationships, like Student is a Person.

Summary

Inheritance lets one class reuse code from another.

It helps organize related classes in a clear way.

It makes code easier to maintain and extend.