These two functions implement the overload of the function!!
1. Default parameters
From this above can be seen, if a function inside, not the necessary parameters, add the corresponding default value, you can complete the corresponding function.
| The code is as follows |
Copy Code |
|
function Overloadfun ($param 1, $param 2 = ' 1 ', $param 3 = True)
{
Do something
} |
Using Functions Func_get_args () and Call_user_func_array ()
PHP Code:
| The code is as follows |
Copy Code |
|
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 ', ' it '); Call Func2 |
2. Use the default value to get the results you want based on the input:
| The code is as follows |
Copy Code |
function Test ($name = "Xiao Li", $age = "23") {
echo $name. "". $age;
}
Test ();
echo "<br/>";
Test ("a");
echo "<br/>";
Test ("A", "B"); |
3. Use the __call ($name, $arg) function for processing.
| The code is as follows |
Copy Code |
|
<?php
class overload{
function __call ($name, $args)
{
& nbsp if ($name = = ' Overloadfun ')
{
switch (count ($args))
{
Case 0: $this->overloadfun0 ();
Case 1: $this->overloadfun1 ($args [0]);
Case 2: $this->overloadfun2 ($args [0], $args [1]);
Default://do something
break;
}
}
function overloadFun0 ()
{
echo 0;
}
function overloadFun1 ($var 1)
{
echo $var 1;< br> }
function overloadFun2 ($var 1, $var 2)
{
echo $var 1+ $var 2;
}
}
$test =new overload ();
$test->overloadfun (). " <br/> ".
$test->overloadfun (1). " <br/> ".
$test->overloadfun (1,2). " <br/> ";
?>
|
With this method we can use them to implement simple function overload, but one thing to note is that PHP as a weak type language, itself can not be as strong as the Java, C + +, the direct implementation of the overload, at least now can not later version will have we do not know,