For weakly typed languages, PHP function overloading is not as normal as OOP.
Because a function overload must meet two conditions:
1, the number of function parameters is different.
2. The type of the parameter is different.
These two points, PHP has no way to meet, you can add more parameters to the function, but the equivalent of more than a temporary variable. Weak types are inherently indistinguishable, so they cannot be implemented.
However, it is possible to implement a simple pseudo-overload by using the following method.
1. Default parameters
From this above can be seen, if a function inside, I do not have to fill in the parameter to add the corresponding default value, you can complete the corresponding function.
function Overloadfun ($param 1, $param 2 = ' 1 ', $param 3 = True) { //do something }
2, using the function Func_get_args () and Call_user_func_array (), detailed help refer to the PHP manual.
A call is made using a regular function to facilitate unified management.
function Overloadfun () { //Overloadfun can be arbitrarily defined, but in order to name the specification, it is recommended that the baby is the same as this function name, //Trailing value is the number of parameters to facilitate management $name = " Overloadfun ". Func_num_args (); return Call_user_func_array (Array ($this, $name), Func_get_args ()); } function OverloadFun0 () { //do something } function overloadFun1 () { //do something } function overloadFun2 () { //do something }
3, using the call ($name, $arg) function for processing.
function call ($name, $args) { if ($name = = ' Overloadfun ') { switch (count ($args)) {case 0: $ This->overloadfun0 (); break; Case 1: $this->overloadfun1 ($args [0]); break; Case 2: $this->overloadfun2 ($args [0], $args [1]); break; Default://do something break ; }}} function OverloadFun0 () { //do something } function overloadFun1 () { //do something } function overloadFun2 () { //do something }
Summary, these methods, can be implemented pseudo-overloaded, the basic 2nd and 3rd, the content can be mutually processed judgment.
This article only gives the method, there may be many details where the need to deal with, for example, to determine the integer type, category and so on.
However, based on the above, PHP may never have a real reload, which would lose the meaning of the language itself.