What is method overloading and method overriding?

@mit $ingh. May 01, 2015 Comments

Method overloading

A class having a method with same name with different  number of parameters, sequence of parameters is called method overloading.

class A {
    public function func1($var1) {
        echo "hello from func1 with parameter as var1";
    }
 
    public function func1($var1,$var2) {
        echo "hello from func1 with parameter as var1 and var2";
    }
}
 
$objA = new A;
$objA->func1('a');

Method overriding

A class having the same name , same access specifiers , same number of parameters as it is in the parent class than we can say it is method overriding .

class A {
 
    public function test($param) {
        echo "\n Parent - the parameter value is $param";
    }
}
 
class B extends A {
 
    public function test($param) {
        echo "\n Child - the parameter value is $param";
    }
}
 
$objA = new A;
$objB = new B;
 
$objA->test('class A');
$objB->test('class B');

Example of method overloading in PHP

class A {
 
    public function __call($method_name,$arguments) {
 
        $methodArray = array('func','func1','func2');
 
        if (in_array($method_name,$methodArray) === false) {
            die("\n Method does not exist");
        }
 
        if (count($arguments) === 2) {
            $this->func($arguments[0],$arguments[1]);
        }
        elseif (count($arguments) === 1) {
            $this->func($arguments[0]);
        }
        elseif (count($arguments) === 0) {
            $this->func();
        }
        else {
            echo "\n unknown method";
            return false;
        }
    }
    function func($a = null,$b = null) {
        echo "\n <br/> from function func, arguments = $a $b";
    }
 
    function func1($a = null) {
        echo "\n <br/> from function func1";
    }
 
    function func2($a = null,$b = null) {
        echo "\n <br/> from function func2";
    }
 
} //
 
$objA = new A;
$objA->func('a');
$objA->func('a','b');
$objA->func('c');
$objA->func();

 

  • PHP
  • method-overloading
  • method-overriding