← back to the blog


php Overloading example

Posted on October 3rd, 2018 in PhP by George
<?php
class RealOverloading{
protected const initialNr = 0;
function __call($name,$arguments)
{
if($name === 'addNumbers'){
switch(count($arguments)){
case 0:
return self::initialNr;
case 1:
return $arguments[0] + self::initialNr;
case 2:
return $arguments[0] + $arguments[1];
case 3:
return $arguments[0] + $arguments[1] + $arguments[2];
}
}
elseif ($name === 'multiplyNumbers'){
switch(count($arguments)){
case 0:
return 0;
case 1:
return $arguments[0];
case 2:
return $arguments[0] * $arguments[1];

case 3:
return $arguments[0] * $arguments[1] * $arguments[2];
}
}
}
}
$obj = new RealOverloading();
//create method
var_dump($obj->addNumbers(5));
//overload method
var_dump($obj->addNumbers(5,6));
var_dump($obj->addNumbers(5,7,'7'));
var_dump($obj->multiplyNumbers(5));
var_dump($obj->multiplyNumbers(8,8));
var_dump($obj->multiplyNumbers(5,7,9));
?>