PHP function overloading
To over load a function simply do pass parameter as null by default,
class ParentClass
{
function mymethod($arg1 = null, $arg2 = null, $arg3 = null)
{
if( $arg1 == null && $arg2 == null && $arg3 == null ){
return 'function has got zero parameters <br />';
}
else
{
$str = '';
if( $arg1 != null )
$str .= "arg1 = ".$arg1." <br />";
if( $arg2 != null )
$str .= "arg2 = ".$arg2." <br />";
if( $arg3 != null )
$str .= "arg3 = ".$arg3." <br />";
return $str;
}
}
}
// and call it in order given below ...
$obj = new ParentClass;
echo '<br />$obj->mymethod()<br />';
echo $obj->mymethod();
echo '<br />$obj->mymethod(null,"test") <br />';
echo $obj->mymethod(null,'test');
echo '<br /> $obj->mymethod("test","test","test")<br />';
echo $obj->mymethod('test','test','test');
You cannot overload PHP functions. Function signatures are based only on their names and do not include argument lists, so you cannot have two functions with the same name. Class method overloading is different in PHP than in many other languages. PHP uses the same word but it describes a different pattern.
You can, however, declare a variadic function that takes in a variable number of arguments. You would use func_num_args()
and func_get_arg()
to get the arguments passed, and use them normally.
For example:
function myFunc() {
for ($i = 0; $i < func_num_args(); $i++) {
printf("Argument %d: %s\n", $i, func_get_arg($i));
}
}
/*
Argument 0: a
Argument 1: 2
Argument 2: 3.5
*/
myFunc('a', 2, 3.5);
PHP doesn't support traditional method overloading, however one way you might be able to achieve what you want, would be to make use of the __call
magic method:
class MyClass {
public function __call($name, $args) {
switch ($name) {
case 'funcOne':
switch (count($args)) {
case 1:
return call_user_func_array(array($this, 'funcOneWithOneArg'), $args);
case 3:
return call_user_func_array(array($this, 'funcOneWithThreeArgs'), $args);
}
case 'anotherFunc':
switch (count($args)) {
case 0:
return $this->anotherFuncWithNoArgs();
case 5:
return call_user_func_array(array($this, 'anotherFuncWithMoreArgs'), $args);
}
}
}
protected function funcOneWithOneArg($a) {
}
protected function funcOneWithThreeArgs($a, $b, $c) {
}
protected function anotherFuncWithNoArgs() {
}
protected function anotherFuncWithMoreArgs($a, $b, $c, $d, $e) {
}
}