Overloading in PHP

Method Overloading in OOP ?

Overloading in oop is same as overloading in real word. In real word overloading means assigning extra work to same machine or person. In oop method overloading is same. By process of method overloading you are asking your method to some extra work. Or in some cases we can say some different work also.

Normally method overloading in oop is managed on the basis of the argument passed in function. We can achieve overloading in oop by providing different argument in same function.

Implementation of overriding can not be achieved by creating 2 function with same name and different argument in php. Because we can not create same name function more than 1 time in php class. To implement overloading we need to take help of magic method in php. In below section we will explore overloading.

Overloading in PHP

As we know that we can not implement overloading by create 2 function in with same name in class. So to implement overloading in php we will take help of magic method __call. Magic method __call invoked when method called by class object is not available in class. So here we will not create method exactly and will take help of __call method. Now call method will provide us 2 argument, 1st name of the method called and parameter of the function. Now with the help of either switch , case or if else we will implement overloading in php. Following is very simple example of overloading in php.

As in above class test magic method __call is implemented which is managing overloading

As we know that __call magic method invoked when method is not available in the class. So in case of above test class example we have not created function overlodedFunction. So whenever method overlodedFunction is called __call invoked. __call pass 2 variable, first  name of the called method and other is parameter passed in the called function.

Now in the __call function I have applied if condition to ensure that our business logic of overloading works only for overlodedFunction function. In if block we have counted number of argument in parameter and applied business logic.