Open In App

How to implement method overloading in PHP ?

Improve
Improve
Like Article
Like
Save
Share
Report

PHP stands for Hypertext Preprocessor, it is a popular general-purpose scripting language that is mostly used in web development. It is fast, flexible, and pragmatic and the latest versions of PHP are object-oriented which means you can write classes, use inheritance, Polymorphism, Data Abstraction, Encapsulation, Constructor, Destructor, and as well as Overloading (Method and Function).

Overloading: Overloading is an Object-Oriented concept in which two or more methods have the same method name with different arguments or parameters (compulsory) and return type (not necessary). It can be done as Constructor Overloading, Operator Overloading, and Method Overloading.
In this article, we will be implementing method overloading in PHP.

Method overloading in PHP:

Example: Given below code will be showing some error. 

PHP




<?php
  
class GFG {
    function multiply($var1){
        return $var1;
    }
      
    function multiply($var1,$var2){
        return $var1 * $var1 ;
    }
}
  
$ob = new GFG();
$ob->multiply(3,6);
?>


 

Output: The error is shown because we are redeclaring function multiply() in GFG Class.

PHP Fatal error:  Cannot redeclare GFG::multiply()

Note: In other programming languages like C++, this will work for overloaded methods. To achieve method overloading in PHP, we have to utilize PHP’s magic methods __call() to achieve method overloading.

__call(): In PHP, If a class executes __call(), and if an object of that class is called with a method that doesn’t exist then, __call() is called instead of that method. The following code demonstrates this.

Example:

PHP




<?php
  
class GFG {  
    public function __call($member, $arguments) {
        $numberOfArguments = count($arguments);
  
        if (method_exists($this, $function = $member.$numberOfArguments)) {
            call_user_func_array(array($this, $function), $arguments);
        }
    }
    
    private function multiply($argument1) {
        echo $argument1;
    }
  
    private function multiply2($argument1, $argument2) {
        echo $argument1 * $argument2;
    }
}
  
$class = new GFG;
$class->multiply(2); 
$class->multiply(5, 7);
  
?>


Output:

35


Last Updated : 30 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads