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

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.

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.