Method Overloading in PHP


Method Overloading:


This type of overloading is for creating dynamic methods that are not declared within the class scope. PHP method overloading also triggers magic methods dedicated for the appropriate purpose.

Unlike property overloading, PHP method overloading allows function call in both object and static context. The related magic functions are,

  • __call()triggered while invoking overloaded methods in the object context.
  • __callStatic()triggered while invoking overloaded methods in static context.

Let us call the undefined class function with both object reference and with the class name itself. For accessing function from outside class with the name of the class itself, it should be a static member of that class. So accessing some overloaded method with the name of the class will trigger static magic member defined within the class. For example


Program:


<?php

class MethodOverloading

{

   public function __call($name, $arguments)

   {

       // Note: value of $name is case sensitive.

       echo "Calling object method '$name' "

            . implode(', ', $arguments). "\n";

   }

public static function __callStatic($name, $arguments)

   {

       echo "Calling static method '$name' "

            . implode(', ', $arguments). "\n";

   }

}

$obj = new MethodOverloading;

$obj->runTest('in object context');

MethodTest::runTest('in static context');

?>


Output:

Calling object method 'runTest' in object context

Fatalerror:Class'MethodTest'notfound in C:\wamp\www\webpage\methodoverloading1.php on line 18

Custom Search

%d bloggers like this: