PHP's friends know that PHP itself is not a function overload of the said, not to mention the use of methods like java,c, but if we dig deeper we will find that you can use the Func_get_args () and Func_num_args () functions in PHP to implement function overloading, Here are two examples of function overloading. These two functions implement overloading of functions.
1, the default parameters, if a function inside, this is not required parameters, and add the corresponding default value, you can complete the corresponding function, the code is as follows:
The code is as follows:
function Overloadfun ($param 1, $param 2 = ' 1 ', $param 3 = True) { //do something }
Using the Functions Func_get_args () and Func_num_args (), the PHP code is as follows:
The code is as follows:
function rewrite () { $args = Func_get_args (); if (Func_num_args () = = 1) { func1 ($args [0]), } else if (Func_num_args () = = 2) { func2 ($args [0], $args [1]); } } function Func1 ($arg) { echo $arg; } function Func2 ($arg 1, $arg 2) { echo $arg 1, ', $arg 2; } Rewrite (' PHP '); Call func1 rewrite (' PHP ', ' China ');//Call Func2
2, use the default value, so according to the input, get the result you want, the code is as follows:
The code is as follows:
function Test ($name = "Xiao Li", $age = "All") { echo $name. $age; } Test (); echo "<br/>"; Test ("a"); echo "<br/>"; Test ("A", "B");
3, the use of __call ($name, $arg) function for processing, the code is as follows:
The code is as follows:
<?php class overload{ function __call ($name, $args) { if ($name = = ' Overloadfun ') { Switch (count ($args)) {case 0: $this->overloadfun0 (); Case 1: $this->overloadfun1 ($args [0]); break; Case 2: $this->overloadfun2 ($args [0], $args [1]); break; Default://do something break ; }}} function OverloadFun0 () { echo 0; } function OverloadFun1 ($var 1) { echo $var 1; } function overloadFun2 ($var 1, $var 2) { echo $var 1+ $var 2; } $test =new overload (); $test->overloadfun (). " <br/> ". $test->overloadfun (1). " <br/> ". $test->overloadfun. " <br/> "; ? >
With this method we can use them to implement simple function overloading, but one thing to note is that PHP as a weakly typed language, itself can not be like a strong type, such as java,c++, the direct implementation of overloading, at least now can not later version will not have we do not know.