PHP Inheritance

Inheritance is one of the most important and fundamental concepts of object-oriented programming (OOP) in PHP. It allows developers to write clean, modular, reusable, and well-structured code.

In PHP, inheritance is an OOP mechanism that allows you to create a new class (known as a subclass or child class) from an existing class (known as a parent class or superclass).

In simple terms, inheritance is the process of creating a new class from an existing. The child class automatically inherits all the public and protected properties (attributes) and methods (behaviors) from the parent class.

Along with inherited features, the child class can also add its own additional new functionality or resources to the newly created class apart from the existing parent class. Additionally, the child class can also modify the existing behavior of the parent class by overriding its methods.

Inheritance helps in establishing a hierarchical relationship between classes, which plays a vital role in building scalable, flexible, and maintainable applications. By using inheritance effectively, you can achieve the following benefits:

  • Code reusability
  • Logical class hierarchy
  • Reduced code duplication
  • Easier maintenance
  • Better extensibility

Real-World Examples of Inheritance in PHP


Let us take some real-world applications where inheritance is commonly used to model relationships where one entity is a specialized version of another. These examples will help you to understand how inheritance is useful in real-world PHP applications.

1. User Management System

In many web applications, different types of users exist, but they often share several common properties and behaviors.

  • Parent Class: User
  • Child Classes: Admin, Customer, Editor, Manager

All users may have common attributes and functionality such as:

  • Name
  • Email
  • Password
  • Login functionality

However, each type of user has specific responsibilities:

  • Admin can manage users, roles, and system settings.
  • Customer can browse products and place orders.
  • Editor can create, update, and manage content.
  • Manager can monitor reports and supervise operations.

Inheritance allows you to define shared features once in the parent User class and then extend or customize behavior in child classes based on their roles. This approach reduces code duplication and makes the system easier to manage, extend, and maintain.

2. Banking System

A banking system is a classic real-world example of inheritance.

  • Parent Class: Account
  • Child Classes: SavingsAccount, CurrentAccount, FixedDepositAccount

Common features shared by all account types include:

  • Account number
  • Account holder name
  • Balance
  • Deposit and withdraw operations

However, each account type has its own specific behavior:

  • Savings accounts may earn interest.
  • Current accounts may allow overdraft facilities.
  • Fixed deposit accounts may have lock-in periods.

Using inheritance, you can define common account-related functionality once in the parent Account class, while specialized rules and behaviors are implemented in the respective child classes.

Syntax to Implement Inheritance in PHP


In PHP, you can implement inheritance using the extends keyword in the class definition, followed by the name of parent class. The general syntax for implementing inheritance in PHP is shown below:

class ParentClass {
// Properties and methods
}
class ChildClass extends ParentClass {
// Additional properties and methods
}

In the above syntax,

  • extends is a keyword used to establish a parent–child relationship between two classes.
  • ChildClass is the name of child class that inherits from the parent class. It is also known as the subclass or derived class.
  • ParentClass is the name of parent class from which the child class inherits properties and methods. It is also known as the base class or superclass.

How Child Class Inherits Features of Parent Class?


Inheritance allows a class to inherit properties and behaviors from another class. This concept can be clearly demonstrated by accessing parent class methods through an object of the child class. Let us consider a simple example where the child class inherits the properties and behaviors of the parent class.

<?php
// Creating a parent class.
class Animal {
// Define a method in the parent class.
   public function eat() {
      echo "The animal is eating. \n";
   }
}

// Creating a child class that inherits the parent class.
class Dog extends Animal {
// Define a method inside the child class.
   public function bark() {
      echo "The dog is barking.";
   }
}

// Creating an object of the child class.
$dog = new Dog();

// Calling parent class method (inherited method) using child class object.
$dog->eat();

// Calling child class method.
$dog->bark();
?>

Output:

The animal is eating. 
The dog is barking.

In this example,

  • We have created a parent class named Animal that contains a method called eat(). This method represents a behavior that is common to all animals.
  • Next, we have created a child class that inherits the eat() method from the Animal class. We use the extends keyword to establish an “is-a” relationship between the two classes.
  • Because of inheritance, the Dog class automatically gets access to all public and protected methods of the parent class. This means the child class can use the inherited functionality without redefining it.

Outside the child class, we have created an object of the child class and use that object to access both:

  • the parent class method (eat()), and
  • the child class’s own method

This demonstrates that the child class can reuse functionality defined in the parent class.

This example clearly proves how a child class inherits features (methods and properties) from its parent class in PHP. The Dog class automatically gains access to the eat() method defined in the Animal class, without rewriting the same code. This highlights how inheritance promotes code reusability, clarity, and better program structure.

Examples of Inheritance in PHP


Let us take some basic examples based on the inheritance in PHP.

Example 1:

<?php
class Vehicle {
   public function startEngine() {
      echo "Engine started. \n";
   }
   public function stopEngine() {
      echo "Engine stopped. \n";
   }
}
class Car extends Vehicle {
   public function drive() {
      echo "Car is being driven.";
   }
}
// Creating an object of class Car.
$car = new Car();

// Calling inherited methods of parent class.
$car->startEngine();
$car->stopEngine();

// Calling method defined in child class.
$car->drive();
?>

Output:

Engine started. 
Engine stopped. 
Car is being driven.

Example 2:

<?php
class Animal {
   public $name;
   public function __construct($name){
      $this->name = $name;
   }
   public function speak(){
      echo "Animal speaks \n";
   }
}
class Dog extends Animal{
   public function bark(){
      echo "Woof! \n";
   }
}
// Creating an instance of the child class.
$dog = new Dog("Buddy");

// Accessing inherited properties and methods from the parent class.
echo $dog->name . "\n";
$dog->speak();

// Accessing methods from the child class.
$dog->bark()
?>

Output:

Buddy
Animal speaks 
Woof!

In this example,

  • Dog is a subclass or child class of Animal, which is parent class or superclass.
  • The keyword extends is used to establish this relation.
  • The Dog class acquires all the properties and methods of the Animal class.

Constructor in Inheritance


In PHP, when you create an object of a child class, the behavior of constructor depends on whether the child class defines its own constructor.

  • If the child class does not define a constructor, and a new object is created of that child class, PHP will automatically call the constructor of the parent class.
  • If the child class defines its own constructor, the parent class constructor is not called automatically.

In such cases, you must explicitly call the parent constructor using the parent::__construct() method. The parent:: keyword is used to access methods or constructors of the parent class from within the child class.

Example 3: Child Class Has No Constructor

<?php
class ParentClass{
   public function __construct(){
     echo "ParentClass constructor called!";
   }
}
class ChildClass extends ParentClass{
   // No constructor defined inside the child class.
}
// Creating an object of child class.
$child = new ChildClass();
?>

Output:

ParentClass constructor called!

In this example, even though child class does not have constructor, the parent class constructor is called automatically when an object of the child class is created.

Example 4: Child Class Defines Its Own Constructor

<?php
class ParentClass {
   public function __construct() {
     echo "ParentClass constructor called! \n";
   }
}
class ChildClass extends ParentClass {
   public function __construct() {
     parent::__construct(); // Explicit call to parent class constructor.
     echo "ChildClass constructor called!";
   }
}

$child = new ChildClass();
?>

Output:

ParentClass constructor called! 
ChildClass constructor called!

In this example, the child class defines its own constructor, the parent class constructor is not called automatically. In such cases, we haved explicitly called the parent class constructor using parent::__construct() inside the child class.

Example 5: Parent Class Does Not Have Constructor

If the parent class does not have a constructor, PHP will continue searching up the inheritance chain until it finds a constructor. If no constructor is found in any parent class, then no constructor is executed.

When you create an object of the class, PHP looks for a constructor in the most specific (child) class first. If the child class does not define a constructor, PHP automatically checks the parent class. This process continues up the inheritance hierarchy. If a constructor is found, it is executed. If no class in the hierarchy defines a constructor, then nothing is executed.

<?php
class A {
   // No constructor
}
class B extends A {
   // No constructor
}
class C extends B {
   // No constructor
}

$obj = new C();
?>

Result: No constructor is executed, because none exists in the inheritance chain.

Example 6: Constructor Found in Higher Chain

<?php
class A {
   public function __construct() {
     echo "Constructor in A";
   }
}
class B extends A {
   // No constructor
}
class C extends B {
   // No constructor
}
$obj = new C();
?>

Output:

Constructor in A

In this example, PHP searches upward for a constructor until it finds a constructor in class A.

Types of Inheritance in PHP


PHP supports the following types of inheritance:

  • Single Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Multiple Inheritance (achieved using Traits, not directly supported by classes)

You will learn about these types in more detail in the next tutorial.