Q:

PHP program to demonstrate the method overloading based on the number of arguments

belongs to collection: PHP Classes & Objects Programs

0

Here, will implement the addition of numbers using method overloading based on a number of arguments. Here, we will use the magic function __call() to implement method overloading in PHP.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to demonstrate the method overloading based on the number of arguments is given below. The given program is compiled and executed successfully.

<?php
//PHP program to demonstrate the method overloading
//based on the number of arguments.
class Sample
{
    function __call($function_name, $args)
    {

        if ($function_name == 'sum')
        {
            switch (count($args))
            {
                case 2:
                    return $args[0] + $args[1];
                case 3:
                    return $args[0] + $args[1] + $args[2];
            }
        }
    }
}

$obj = new Sample();

printf("Sum: " . $obj->sum(10, 20) . "<br>");
printf("Sum: " . $obj->sum(10, 20, 30) . "<br>");
?>

Output:

Sum: 30
Sum: 60

Explanation:

Here, we created a class Sample and then implemented magic function __call() to perform method overloading to add numbers based on the number of arguments. Here, we used switch cases for the number of arguments and return the sum of numbers.

At last, we created the object $obj of the Sample class and the call sum method with a different number of arguments and print the result on the webpage.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP Classes & Objects Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
PHP programs to pass an object of class as an argu... >>
<< PHP program to demonstrate the final keyword...