Tuesday, 14 July 2015

Method Overloading and Method Overriding in PHP

Polymorphism in PHP:
        polymorphism is one of the oops concepts which has the ability to take more than one form.

Types of Polymorphism:
  1. Method Overloading.
  2. Method Overriding.
1. Method Overloading:
      In PHP method overloading is implemented by using magic method __call().

syntax of __call():

      __call (name , arguments);

Example:
    
<?php
class test{
    public function __call($name, $arguments)
    {
        if ($name === 'test'){
            if(count($arguments) === 2 ){
                return $this->sum_of_two($arguments[0],$arguments[1]);
            }
            if(count($arguments) === 3){
                return $this->sum_of_three($arguments[0], $arguments[1],$arguments[2]);
            }
        }
else{
echo "not valid";
}
    }

    private function sum_of_two($data1,$data2)
    {
       echo "sum of two arguments is :" . " ". ($data1+$data2). '<br>';
    }

    private function sum_of_three($data1,$data2,$data3)
    {
       echo"sum of three arguments is :" . " " . ($data1+$data2+$data3) .'<br>';
    }
}

$test = new test();
$test->test(1,2); 
$test->test(1,3,4);
?>

output:
     sum of two arguments is : 3
     sum of three arguments is: 8

2. Method Overriding:
        Method overriding means, overriding the superclass method by subclass method and both will have the same method name.

Example:

<?php
  class super{
 public function demo(){
 echo "This is the super class method";
 }
  }
  class sub extends super{
 public function demo(){
 echo "This is the child class method";
 }  
  }
  $obj=new sub();    //object creation
  $obj->demo();      // calling demo method

 ?>

output
      This is the child class method