Overloading in PHP

Introduction to Overloading

Overloading is another important and useful concept of OOP (object oriented programming). In overloading programmer create many functions with the same name and in the same class but there is a restriction that all these functions must have something different in it from others like its return type, its number of argument and its data type of arguments. we have already discussed in detail about the concept of overloading in Java. In this tutorial, you will learn about overloading in PHP, which is different from other languages.

Like if you want to do overloading in Java the code will like:

All the function above have the same name which is the result, but they all have something different among themselves, so this concept is called overloading and also known as early binding or static binding.

Overloading in PHP

The all above description is valid if you are working in some other programming language like C, C++, Java, C#, etc. but PHP denied this concept of overloading.

Some things must be remembered before starting overloading in PHP.

  • You are not able to overload PHP functions.
  • Only class functions can be overloaded in PHP.
  • As PHP have no data type issue, so it’s difficult to overload any function by the return type.
  • Arguments in any PHP function is not necessary so that its difficult for the compiler to decide which function will be called.
  • Dynamically creation of methods and properties in PHP is called overloading.

Overloading functions in PHP:

You must remember following functions while implementing the concept of overloading in PHP.

  1. __get() This function is used to read data from inaccessible properties.
  2. __set() This function run when you try to write data in some inaccessible property.
  3. __unset() This property is executed when the unset() function is used on inaccessible properties.
  4. __isset() This function is set or call by calling isset() or empty() function on inaccessible properties.

As the PHP doesn’t support regular method of overloading as in other programming languages, so there is one possible way through which you can overload functions in PHP, this is a magic function __call().

The __call () is called the magic function in PHP is same as __get () was use for class variables. This function executes when you call some function which is not available in class the PHP compiler does not find that function in your class in that case if you have a __call() function this will execute. If so, your _call () is used, with the name of the function you want to call and the parameters you passed being passed in as parameters one and two respectively.

Read More about PHP overloading