PHP

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

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

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

We 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

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>");
?>

 

TutorialsLink Curator

This is an official account managed by the team TutorialsLink Community