Monday, July 14, 2014

Function overloading in PHP with example

General Definition
Defining more than one function with a same name, but different number of parameters or different types of parameters.

In PHP
PHP does not support function overloading directly. That is we cannot create more than one function with a same name under a class, even it has different number of arguments or different data types. But we can do this using a PHP magic method called __call().

__call()
This PHP magic method will be triggered when class object trying to call undefined function(Note: This will not work when we trying to call a undefined function using class name.).
This has two parameters, first one is function name(Undefined function's name which we are trying to call.) and second one is parameters(Undefined function's parameters which we are trying to input.).

Example
<?php
class A
{
function __call($function,$parameters)  // Magic method
{
//echo $function;
//print_r($parameters);
if($function=='test')
{
switch (count($parameters)) {
case "1":
echo 'Test function with one parameters.<br />';
break;

case "2":
echo 'Test function with two parameters.<br />';
break;
case "3":
echo 'Test function with three parameters.<br />';
break;
default:
echo 'Critical Error.<br />';
break;
}
}
else
{
echo $function.' function not exist.<br />';
}
}
}

$a=new A();
$a->test('hi');
$a->test('par1','par2');
$a->test(1,2,3);
$a->sample();
?>

Output
Test function with one parameters.
Test function with two parameters.
Test function with three parameters.
sample function not exist.

No comments:

Post a Comment

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS&l...