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

Here, we are going to demonstrate the method overloading based on the number of arguments in PHP.
Submitted by Nidhi, on November 21, 2020 [Last updated : March 13, 2023]

Method Overloading Based on Number of Arguments

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.

PHP code to implement method overloading based on the number of arguments

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.

PHP Class & Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.