Originally php?name=PHP">PHP does not support function overloading!
As a weakly typed language, php itself cannot directly implement overloading like strongly typed languages such as java and c++. However, 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:
<span>function</span><span> rewrite() { </span><span>$args</span> = <span>func_get_args</span><span>(); </span><span>if</span>(<span>func_num_args</span>() == 1<span>) { func1(</span><span>$args</span>[0<span>]); } </span><span>else</span> <span>if</span>(<span>func_num_args</span>() == 2<span>) { func2(</span><span>$args</span>[0], <span>$args</span>[1<span>]); } } </span><span>function</span> func1(<span>$arg</span><span>) { </span><span>echo</span> <span>$arg</span><span>; } </span><span>function</span> func2(<span>$arg1</span>, <span>$arg2</span><span>) { </span><span>echo</span> <span>$arg1</span>, ' ', <span>$arg2</span><span>; } rewrite(</span>'PHP'); <span>//</span><span>调用func1 </span> rewrite('PHP','China'); <span>//</span><span>调用func2 </span>
2. Use the default value to get the results you want based on the input:
<span>function</span> test(<span>$name</span>="小李",<span>$age</span>="23"<span>){ </span><span>echo</span> <span>$name</span>." ".<span>$age</span><span>; } test(); </span><span>echo</span> "<br/>"<span>; test(</span>"a"<span>); </span><span>echo</span> "<br/>"<span>; test(</span>"a","b");