How Method Overloading Works in PHP

Rmag Breaking News

What is Method Overloading?

Method overloading is a concept & process that allows you to have a method that can perform differently based on its number of parameters. It allows you have multiple definitions for a same method in the same class.

This method will have the same name for all its uses, but might produce different output in different situations. Method overloading is a key concept under the umbrella of polymorphism.

Traditional Overloading

For example, say you have an add method that you want to use to sum a couple of numbers in these ways:

<?php
class SampleClass
{
function add(int $a, int $b): int
{
return $a + $b;
}

function add(int $a, int $b, int $c): int
{
return $a + $b + $c
}

}

$object = new SampleClass();
echo $object->add(2,3) . ” Break “;
echo $object->add(2,3,3);

In reality this show error

PHP Fatal error: Cannot redeclare SampleClass::add() in C:UsersAl-AMIN ISLAMDesktopOverLoading.php on line 9

Fatal error: Cannot redeclare SampleClass::add() in C:UsersAl-AMIN ISLAMDesktopOverLoading.php on line 9

The __call keyword

This is a magic method that PHP calls when it tries to execute a method of a class and it doesn’t find it. This magic keyword takes in two arguments: a function name and other arguments to be passed into the function. Its definition looks like this:

function __call(string $function_name, array $arguments) {}

For example, to achieve our intended goal with the add function, update the __call definition and your SampleClass to be like this:

<?php
class SampleClass
{
function __call($function_name, $arguments)
{
$count = count($arguments);
if($function_name == “add”){
if($count== 2){
return array_sum($arguments);
}elseif($count == 3){
return array_sum($arguments);
}
}
}

}

$object = new SampleClass();
echo $object->add(2,3) . ” Break “; // Outputs 5
echo $object->add(2,3,3); // Outputs 8

The code is pretty self explanatory. Here’s a step by step breakdown:

Use the count method to know how many arguments are passed to your method.

Check the function name being passed in. This __call will house all the different methods you intend to create variations of, so the name should be unique and be used to group variations of the methods.

Handle the logic as you like based on the different number of arguments. Here, we return the sum

When you call the add method, PHP checks for a method with the same name in the class, if it doesn’t find it, it calls the __call method instead, and that is how the code is run.

Leave a Reply

Your email address will not be published. Required fields are marked *