Example of PHP function overloading tips
|
Php, as a weak type language, cannot directly implement overload like a strong type such as java or c ++.
Function overloading can be indirectly implemented through some methods.
1. you can use the func_get_args () and func_num_args () functions to overload functions.
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
2. use the default value to obtain the desired result based on the input:
- Function test ($ name = "Xiao Li", $ age = "23 "){
- Echo $ name. "". $ age;
- }
- Test ();
- Echo"
";
- Test ("");
- Echo"
";
- Test ("a", "B ");
|