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.
When multiple methods exist within the same class with the same name but different in signatures.
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()
Example:
<?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?
<?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');
?>