Java-style overloading in PHP
Sometimes it is convenient to have the same method that can invoke variable parameters. PHP's ability to define optional parameters with default values makes this possible.
This method overload can be implemented in PHP5 with __call (). Let's look at an example below. Suppose you want to use overloaded behavior, put it in an abstract parent class.
Abstract class overloadableobject{function __call ($name, $args) {$method = $name. " _ ". Count ($args); if (!method_exists ($this, $method)) {throw new Exception ("Call to Undefined method". Get_class ($this). ":: $method"); } return Call_user_func_array (Array ($this, $method), $args); }}
The main behavior of this class method is $method = $name. " _ ". Count ($args); displays a line of code defined. If the call does not define a method, the __call () method generates a new method whose name is composed of the original method and the number of arguments, separated by underscores. The method is then called with the newly generated method name, and the original parameters are passed together.
Now, if you want to use an overloaded method named multiply, you can use two or three parameters to invoke it, and in each case, you can use two methods, respectively: Multiply_2 and Multiply_3
class Multiplier extends overloadableobject{function multiply_2 ($one, $two) {return $one * $TWO; } function Multiply_3 ($one, $two, $three) {return $one * $two * $three; in order to use this code, only the multiply method with two or three parameters is called.
$multi = new Multiplier;
echo $multi->multiply (5,6). " \ n ";
echo $multi->multiply (5,6,7). " \ n ";
?