What is method overloading in PHP?


Method Overloading is a concept of Object Oriented Programming which helps in building the composite application in an easy way. Function overloading or method overloading is a feature that permits making creating several methods with a similar name that works differently from one another in the type of the input parameters it accepts as arguments.

The above concept is fine for other programming languages and it is called static polymorphic i.e method overloading.

Example

Let's understand through an example.

<?php
   class machine {
      function doTask($var1){
         return $var1;
      }
      function doTask($var1,$var2){
         return $var1 * $var1 ;
      }
   }
   $task1 = new machine();
   $task1->doTask(5,10);
?>

Output:

Error

Explanation:

This will generate an error since php will say you have declared this method twice.
But Other programming languages says , doTask($var1) and doTask($var1,$var2) are overloaded methods. To call the latter, two parameters must be passed, whereas the former requires only one parameter.
so this behavior i.e decision to call a function at coding time is known as static polymorphic i.e method overloading.

Let's discuss how to achieve method overloading related to PHP5.In the case of PHP, we have to utilize PHP's magic methods __call() to achieve method overloading.

In PHP overloading means the behavior of method changes dynamically according to the input parameter. In this tutorial, we will understand those perceptions. Let's discuss the __call() method.

__call():

If a class execute __call(), then if an object of that class is called with a method that doesn't exist then__call() is called instead of that method.

Example

Let's understand method overloading with an example.

<?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] ;
               case 2 : return $arg[0] * $arg[1];
            }
      }
   }
   $circle = new Shape();
   echo $circle->area(3);
   $rect = new Shape();
   echo $rect->area(8,6);
?>

Output:

9.426
48

Explanation:

Here area() method is created dynmically and executed with the help of magic method __call() and it's behaviour changes according to pass of parametrs as object.

Updated on: 31-Dec-2019

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements