Thursday, September 4, 2025
HomeLanguagesHow to implement method overloading in PHP ?

How to implement method overloading in PHP ?

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
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS