pTutorial

New way to learn PHP

PHP 5 Method overloading

Function overloading

In General Function overloading

Function overloading or method overloading is an object oriented features of programming languages. You can perform different types of task by using a single method by changing the number of argument or data type. PHP does not support the two methods with the same name in a class with different parameter.

Example of overloading

<?php

class Student 
{
public function setName($a)
{  
echo " Single parameter $a";
}

public function setName($a, $b) {

echo "Method with two parameter";
}
}

?>

Output

Fatal error: Cannot redeclare Student::setName()

If the above code converts according to the Java or C++ syntax it will run properly without any error. But if we execute the above code in PHP, it will throw exception "Cannot redeclare STUDENT:: setName ()".

Function overloading in PHP

To achieve the Function overloading magic method __call is used. __call method is called when undefined (undeclared) method of the class is called with the help of the object.

Example of PHP method overloading

<?php

class Computer {
    public function __call($name, $arguments) {
        if ($name === 'findSum') {
            echo 'Sum : ' . $this->add($arguments)."
"; } else { echo "Name of method $name"."
"; } } private function add($arguments) { $sum = 0; foreach ($arguments as $argument) { $sum += $argument; } return $sum; } } $Computer = new Computer; $Computer->findSum(10); $Computer->findSum(10,20); $Computer->findSum(10.20,20.50,30.50); ?>

Output

Sum : 10
Sum : 30
Sum : 61.2


QUOTES OF THE DAY

Each day provides its own gifts.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER