Function Overloading and Overriding in PHP

Function overloading and overriding are important object-oriented programming concepts in PHP that allow you to create flexible and reusable code structures.

Function Overloading in PHP

Function overloading is a feature that permits creating several methods with a similar name that works differently from one another based on the type or number of input parameters it accepts as arguments. PHP achieves this through the magic method __call().

Example

Let us now see an example to implement function overloading −

<?php
    class Shape {
        const PI = 3.142;
        
        function __call($name, $arg) {
            if($name == 'area')
                switch(count($arg)) {
                    case 0: return 0;
                    case 1: return self::PI * $arg[0]; // Circle area
                    case 2: return $arg[0] * $arg[1];  // Rectangle area
                }
        }
    }
    
    $circle = new Shape();
    echo "Circle area: " . $circle->area(3) . "
"; $rect = new Shape(); echo "Rectangle area: " . $rect->area(8, 6); ?>

Output

This will produce the following output −

Circle area: 9.426
Rectangle area: 48

Function Overriding in PHP

In function overriding, the parent and child classes have the same function name with the same number of arguments. The child class method overrides the parent class method when called on a child object.

Example

Let us now see an example to implement function overriding −

<?php
    class Base {
        function display() {
            echo "Base class function declared final!
"; } function demo() { echo "Base class function!
"; } } class Derived extends Base { function demo() { echo "Derived class function!
"; } } $ob = new Base; $ob->demo(); $ob->display(); $ob2 = new Derived; $ob2->demo(); $ob2->display(); ?>

Output

This will produce the following output −

Base class function!
Base class function declared final!
Derived class function!
Base class function declared final!

Key Differences

Feature Function Overloading Function Overriding
Implementation Uses __call() magic method Child class redefines parent method
Parameters Different number/type of parameters Same method signature
Class Relationship Single class Inheritance required

Conclusion

Function overloading allows multiple behaviors for the same method name using __call(), while function overriding enables child classes to provide specific implementations of parent methods. Both techniques enhance code flexibility and reusability in PHP applications.

Updated on: 2026-03-15T08:22:28+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements