Method Overriding in PHP: Rules, Examples

Method overriding in PHP is one of the most important concepts of object-oriented programming (OOP). It allows a child class to provide its own specific implementation of a method that is already defined in its parent class.

When the method of parent class is overridden in the child class to provide more specific implementation, it is called method overriding. This feature allows a child class to replace, customize, or extend the functionality of an inherited method from its parent class according to its own requirements.

Method overriding is widely used in real-world PHP applications such as Laravel, Symfony, WordPress plugins, payment systems, and API, where PHP developers need to modify or extend existing functionality (or behavior) without changing the parent class code.

Why Use Method Overriding in PHP?


Method overriding is used to:

  • Achieve runtime polymorphism, where the method call is resolved at runtime based on the object type.
  • Extend or customize parent class functionality without modifying the existing code in the parent class.
  • Improve code flexibility and maintainability by allowing behavior changes in child classes.
  • Follow the Open/Closed Principle, where classes are open for extension but closed for modification.
  • Implement different behaviors for different child classes using the same method name.

Syntax of Method Overriding in PHP


The basic syntax of implementing method overriding in PHP is given below:

<?php
class ParentClass {
   public function methodName() {
     // Parent class method code
   }
}
class ChildClass extends ParentClass {
   public function methodName() {
    // Child class method code (overridden method)
   }
}
?>

In the above syntax of method overriding,

  • ParentClass is the parent class or superclass, which contains a method named methodName().
  • ChildClass is the child class or subclass that extends the parent class using extends keyword.
  • The child class defines a method with the same name as parent class method. Both methods have the same name and a compatible method signature.
  • The method defined in the child class overrides the method of the parent class.

Rules for Method Overriding in PHP


Method overriding in PHP occurs when a child class defines a method with the same method name and a compatible method signature as the method in the parent class. This means:

  1. The method name must be the same in both the parent and child classes.
  2. The parameter list must be compatible, not necessarily strictly identical.
    • The number of required parameters must not be reduced.
    • Additional parameters in the child class must be optional.
    • Parameter types must follow PHP’s variance rules.
  3. The return type of the child class method must be compatible with the parent class method’s return type. It must be the same or covariant (more specific) return type.
  4. The access modifier of the child class method must be the same or less restrictive than that of the parent class method.
    • During the overriding, you can increase the visibility of the overriding method but cannot reduce it.
    • For example, a protected method in the parent class can be overridden as public in the child class, but not as private.
  5. PHP does not allow overriding static methods because the compiler resolves them at compile time, not at runtime.
  6. You cannot also override final methods in PHP.
Note:

If method signatures are incompatible, the method is not considered a valid method overriding in PHP, and PHP will throw a fatal error.

Example of Method Overriding in PHP


Let us take some important examples based on the method overriding in PHP that you must practice them.

Example 1: Basic Method Overriding

<?php
// Declare a parent class.
class Animal {
// Method defined in the parent class.
   public function sound() {
     echo "Animal makes a sound!";
   }
}
// Declare a child class that extends the parent class.
class Dog extends Animal {
// Overriding the inherited sound() method of the parent class.
   public function sound() {
      echo "Dog barks!";
   }
}
// Creating an object of the child class.
$dog = new Dog();

// Calling the overridden method in the child class.
$dog->sound();
?>

Output:

Dog barks!


In this example:

  • The Animal class is the parent (base) class. It contains a method named sound() that displays a message “Animal makes a sound!”.
  • The Dog class is a child (subclass) that extends the Animal class.
  • The Dog class overrides the inherited sound() method of the parent class.
  • Both methods have the same name, parameters, and access modifier.
  • When an object of the Dog class is created, the sound() method of the child class is called.
  • This example demonstrates runtime polymorphism in PHP.

Example 2: Method Overriding with Parent Method Access

Sometimes, you need to use both the parent and child class methods. In such cases, you can use the parent:: keyword provided by PHP to call the parent class method from within the overridden child class method..

<?php
class Vehicle {
   public function start() {
     echo "Vehicle started. \n";
   }
}
class Car extends Vehicle {
   public function start() {
   // Calls the start() method of the parent (Vehicle) class.
      parent::start();
   // Additional behavior specific to the Car class.
      echo "Car is ready to drive. \n";
   }
}
// Creating an object of class Car.
$car = new Car();
// Calling inherited start() method of child class.
$car->start();
?>

Output:

Vehicle started. 
Car is ready to drive.

In this example:

  • Vehicle is the parent (base) class. The start() method in the Vehicle class prints a message “Vehicle started.”.
  • Car is a child class that extends the Vehicle class.
  • The Car class overrides the inherited start () method of the parent class.
  • Inside the overridden method, the parent::start() is used to call the parent class’s start() method. This ensures that the original behavior of the parent class is executed.
  • After calling the parent method, the child class adds its own specific implementation.
  • This approach allows the child class to extend, but not completely replace the parent class functionality.

Example 3: Method Overriding with Access Modifiers

When you are overriding, you can increase the visibility of the overriding method but cannot reduce it. Let’s take an example on it.

<?php
class ParentClass {
 // Protected method in the parent class.
    protected function display() {
      echo "Parent class method";
    }
}
class ChildClass extends ParentClass {
 // Overriding the protected method of the parent class.
 // Here, we have increased the visibility from protected to public, which is allowed.
    public function display() {
       echo "Child class method";
    }
}

// Creating an object of the child class.
$obj = new ChildClass();
// Calling the overridden method.
$obj->display();
?>

Output:

Child class method

In this example:

  • ParentClass is the parent class (superclass), which contains a display() method with a protected access modifier.
  • You can access a protected method within the same class and inside child classes, but you cannot access it directly from outside the class.
  • ChildClass is the child class, which extends ParentClass.
  • The display() method in ChildClass overrides the method defined in the parent class.
  • Since the access modifier of the parent class method is protected and the access modifier of the child class method is public, the visibility is increased.
  • Increasing visibility is allowed, but reducing visibility is not allowed while overriding a method in PHP.
  • When the method is called using a child class object, the display() method of the child class is executed.

Method Overriding with Type Hinting (PHP 7+)


From PHP 7 onwards, PHP supports type hinting and return type declarations, which makes method overriding more strict and reliable.

When you are overriding a method in a child class, the return type of an overridden method must be the same as the return type of the parent method or covariant (more specific) starting from PHP 7.4.

Using an incompatible return type will result in a fatal error. This compatibility rule helps to prevent unexpected return values and ensures better code readability, reliability, and maintainability.

Example 4: Return Type in Method Overriding

<?php
class Shape {
// Declare a method with return type declaration.
   public function getName(): string {
     return "Shape";
   }
}
class Circle extends Shape {
// Overriding method with the same return type.
   public function getName(): string {
     return "Circle";
   }
}
$circle = new Circle();
echo $circle->getName();
?>

Output:

Circle

In this example:

  • The Shape class is the parent class, which contains a method getName() that must return a string, as specified by : string.
  • The Circle class is a child class that extends Shape class.
  • The getName() method in Circle overrides the parent class method.
  • The child method uses the same return type (string), which is required for valid overriding.
  • When the method is called using an object reference variable of child class Circle, the child class method is executed.

Conclusion

Method overriding in PHP is a powerful feature of object-oriented programming that allows a child class to customize or extend the behavior of a method inherited from the parent class while maintaining a compatible method signature. It helps achieve runtime polymorphism as well as improves code flexibility and reusability.

We hope this article has helped you understand the basic concept of method overriding in PHP and how to implement it effectively using practical examples.