In this tutorial, you will learn the method overloading, in PHP Overloading and Overriding are forms of polymorphism in OOP. According to Overloading Concept, Two or more methods have the same name but different parameters.
It is also called static polymorphism, compile-time, and Early binding polymorphism.
Method Overloading in PHP
PHP does not support method overloading compared to other languages like Java or C++. To overcome this functionality interfaces and abstract class plays important role in PHP. However we can achieve this functionality by magic function like __Call()
Why Method Overloading is an Advantage in Oops
- Overloading is used when you want to extend the functionality.
- Overloading is known as compile time polymorphism
Examples of Method Overloading
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php class Student { public function StudentName($param1) { echo "Name of the Student:". $param1; } public function StudentName($param1,$param2) { echo "Name of the Student:".$param1; echo "Age of the Student:".$param2; } } $obj1 = new Student; $obj1->StudentName('Praveen'); $obj1->StudentName('Rajib','20'); ?> |
But, In PHP this will throw fatal Error. Incase of C++, and Java it will work fine. To overcome this we can use __Call().
How to Use __Call() to achieve this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <?php class Student { public function __call($method_name, $arguments){ $methodArray = array('studentname1','studentname2'); if (in_array($method_name,$methodArray) === false) { die("Method does not exist"); } if (count($arguments) === 2) { $this->studentname2($arguments[0],$arguments[1]); } elseif (count($arguments) === 1) { $this->studentname1($arguments[0]); }else{ echo "unknown method"; return false; } function studentname1($var1) { echo "Name of the Student:".$var1; } function studentname2($var1,$var2){ echo "Name of the Student:".$var1; echo "Age of the Student:".$var2; } } $obj1 = new Student; $obj1->studentname1('Praveen'); $obj1->studentname2('Nagesh','24'); ?> |