Overloading in PHP with Example

Swapnil
No Comments

Function overloading or method overloading is a feature that allows creating several methods with the same name which differ from each other in the type of the input parameters. It is simply defined as the ability of one function to perform different tasks. For example, doTask() and doTask(object O) are overloaded methods. To call the latter, an object must be passed as a parameter, whereas the former does not require a parameter, and is called with an empty parameter field. It is a form of static polymorphism which .The decision to call an implementation or another is taken at coding time.

Lets take the famous area example which will calculate the area depending on the number of inputs given:

<?php
/*
 * Don't try this at home, will be fatal !!

class Shape {
 function area(){
  return 0 ;
 }
 function area($radius){
  return PI * $radius * $radius ;
 }
 function area($length,$breadth){
  return $length * $breadth ;
 }
}

$circle = new Shape();
$circle->area(5);

$rect = new Shape();
$rect->area(5,10);
*/

 

This is erroneous ┬ásince php will say you have declared this method twice . Other languages says its fine and calls it static polymorphic i.e method overloading. You have to use PHP’s magic methods to achieve method overloading in PHP.

<?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(5);


$rect = new Shape();
echo $rect->area(5,10);

 

0 responses to “Overloading in PHP with Example”

  1. Anant says:

    the most easiest and fine example among all links. Great work Mate

  2. prncy says:

    Fantastc ….clear explanaton ..Than u

  3. Munir says:

    Thank you very much to describe overloading in PHP so easily. I found it in so many sites but this seem me more easy than the others.

  4. amildirin raja says:

    great example

Leave a Reply

Your email address will not be published. Required fields are marked *

Search