php, as a weakly typed language, cannot directly implement overloading like strongly typed languages such as java and c++.
Function overloading can be achieved indirectly through some methods.
1. You can use the two functions func_get_args() and func_num_args() to implement function overloading. php 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]);
- }
- } www.jbxue.com
- function func1($arg) {
- echo $arg;
- }
- function func2($arg1, $arg2 ) {
- echo $arg1, ' ', $arg2;
- }
- rewrite('PHP'); //Call func1
- rewrite('PHP','China'); //Call func2
Copy code
2. Use the default value to get the results you want based on the input:
- function test($name="小李",$age="23"){
- echo $name." ".$age;
- }
-
- test();
- echo "
test("a"); - echo "
";
- test("a","b");
Copy code
|