Posted by: phillipnb | September 1, 2011

Method Overloading and Method Overriding in Object Oriented PHP


In PHP a method can have zero or more parameters. In some programming languages the parameter type should also be declared. According to Object Oriented Programming(OOP) concept if a class has methods of the same name but different parameters then we say that we are overloading that method. It is a form of polymorphism in OOP.

So, for a programming language like C, the function add(int,float) is different from add(float,int) or even add(float,int,int). But this is not the case with PHP because

  • PHP is not type strict
  • PHP methods allow variable number of arguments.

Hence achieving polymorphism in PHP is difficult but as we read the remaining of this article we can see how PHP was able to achieve polymorphism.

Method Overloading

Though PHP 5 has implemented many OOP features, it cannot demonstrate a real method overloading as seen in other programming languages like java or c++. for example:

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');

If the above example were to be converted to java or c++, it will work without any errors but not in PHP. If we were to run the above example in PHP, it will throw the error “Cannot redeclare A::func1()”. But don’t be disappointed. We may not be able to achieve an exact method overloading as in java or c++ but still we can achieve an “overloading like functionality” in PHP using the magic method called __call(). for example:

class A {

    public function __call($method_name,$arguments) {

        $methodArray = array('func1','func2');

        if (in_array($method_name,$methodArray) === false) {
            die("\n Method does not exist");
        }

        if (count($arguments) === 2) {
            $this->func2($arguments[0],$arguments[1]);
        }
        elseif (count($arguments) === 1) {
            $this->func1($arguments[0]);
        }
        else {
            echo "\n unknown method";
            return false;
        }
    }
	function func1($a) {
	    echo "\n from func1($a)";
	}

	function func2($a,$b) {
	    echo "\n from func2($a,$b)";
	}

} //

$objA = new A;
$objA->func1('a');
$objA->func2('a','b');
$objA->func3('c');

Updated on 31st July 2013 – The above code does show how _call works in php. In order to achieve function overloading, we need to use the following example:


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

__call() function is triggered when invoking inaccessible methods in an object context. The syntax for __call() is mixed __call(string $name,array $arguments).

The $name parameter is the name of the method being called. The $arguments parameter is an enumerated array containing parameters passed to the $name method.

Method Overriding

In OOP PHP if we were to create a method in the child class having the same name, same number of parameters and the same access specifier as in it’s parent then we can say that we are doing method overriding. for example:

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');

The definition of polymorphism says that “if the decision to invoke a method is made by inspecting the object at run time then it is a case of polymorphism”. We can apply this rule in our example. Whether to call method test() of class A or class B is decided by inspecting the concerned object which is making the call to the method. Thus the method call will be based on the object.

Hope I was able to explain method overloading and method overriding to you.

Till next time it is Happy PHPing.

About these ads

Responses

  1. thank you.. It helped me.

  2. Bundles of thanks………..
    Your explanation about the overloading and overriding help me to understand the concept….thank you once again……………..

  3. IT DOES NOT MAKE ANY SENSE TO USE DIFFERENT FUNCTION NAME LIKE FUNC1,FUNC2 ETC. THE EXAMPLE YOU GIVEN DOES NOT ACHIEVE FUNCTION OVERLOADING ACTUALLY. INSTEAD THE BELOW CODE WORKS BETTER.
    class Overloading_Test
    {
    function __call($method_name, $arguments)
    {
    //list of supported methods
    //only ‘hello’ for this test
    $accepted_methods = array(“hello”);

    //in case of unexistant method we trigger fatal error
    if(!in_array($method_name, $accepted_methods))
    {
    trigger_error(“Method $method_name doesn’t exist”, E_USER_ERROR);
    }

    //we inspect number of arguments
    if(count($arguments) == 0)
    {
    $this->hello1();
    }
    elseif(count($arguments) == 1)
    {
    $this->hello2($arguments[0]);
    }
    elseif(count($arguments) == 2)
    {
    $this->hello3($arguments[0], $arguments[1]);
    }
    else
    {
    return false;
    }
    }

    function hello1()
    {
    echo “Hello Anonymous”;
    }

    function hello2($name)
    {
    echo “Hello $name”;
    }

    function hello3($first_name, $last_name)
    {
    echo “Hello $first_name, $last_name”;
    }
    }
    echo “########################”;
    $ot = new Overloading_Test();
    $ot->hello();
    $ot->hello(“John”);
    $ot->hello(“John”, “Smith”);

    IN THIS WAY YOU ARE JUST CALLING SINGLE METHOD BY PASSING DIFFERENT ARGUMENTS.

  4. Agreed. As long as you count the number of arguments and use __call() and then branch it to appropriate function, it can definitely be called “overloading” in php.

    Yes, Your example is an improved version but I disagree with your view that “the example in the post/write up is not overloading”.

    • My intention was not to use different function name in your example

      $objA->func1(‘a’);
      $objA->func2(‘a’,’b’);
      $objA->func3(‘c’);

      Instead a single function should be used like used

      $ot->hello();
      $ot->hello(“John”);
      $ot->hello(“John”, “Smith”);

      • Agreed.

  5. There should have been only one function called ‘func’ and the calls should have been
    $objA->func(‘a’);
    $objA->func(‘a’,’b’);
    $objA->func(‘c’);

    • that’s right.

  6. thanx its nice…..

  7. what is the
    defnition of method overriding nd overloading in php?

    • read that post on method overloading and method overriding , again.

  8. nice explanation to understand the basic concept of oops. Thank you…

  9. Nice post ! It Cleared my long time of confusion!

  10. its very useful

  11. it works …. gr8 job… please keep it up…..best of luck

  12. Reblogged this on Srikanth's Blog.

  13. Very nice tutorial

  14. very nice tutorials

  15. if you calling two different functions. how can it satisfy the overloading concept in php?

    • Thank You. This was an error pointed out a few months back, please read all the comments. Anyway – I have updated the contents of this blog.

  16. function say($str = null){
    echo $str? $str: “Hello Wolrd”;
    }

    say();
    say(“Hallo Universe”);

  17. If we have multiple overloaded functions in same class how we have to do..

  18. really great …..thanks please write more about real use of abstract class and interface ………….

  19. really great …..thanks please write more about real use of abstract class and interface ………….

    • Arsh, Will definitely look into your request – hope I find some time-:). Glad that you liked the post on method overloading.

  20. method overriding creating a method with the same return type and signature as a method defined in a supperclass
    method overloading method of the same name declared in the same declared in the same class


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.

Join 25 other followers

%d bloggers like this: