How to implement method overloading in PHP ?
PHP stands for Hypertext Preprocessor, it is a popular general-purpose scripting language that is mostly used in web development. It is fast, flexible, and pragmatic and the latest versions of PHP are object-oriented which means you can write classes, use inheritance, Polymorphism, Data Abstraction, Encapsulation, Constructor, Destructor, and as well as Overloading (Method and Function).
Overloading: Overloading is an Object-Oriented concept in which two or more methods have the same method name with different arguments or parameters (compulsory) and return type (not necessary). It can be done as Constructor Overloading, Operator Overloading, and Method Overloading.
In this article, we will be implementing method overloading in PHP.
Method overloading in PHP:
Example: Given below code will be showing some error.
Output: The error is shown because we are redeclaring function multiply() in GFG Class.
PHP Fatal error: Cannot redeclare GFG::multiply()
Note: In other programming languages like C++, this will work for overloaded methods. To achieve method overloading in PHP, we have to utilize PHP’s magic methods __call() to achieve method overloading.
__call(): In PHP, If a class executes __call(), and if an object of that class is called with a method that doesn’t exist then, __call() is called instead of that method. The following code demonstrates this.