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. Brand website Construction: http://www.ucantech.com/
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.
PHP code
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 kind of method is in
PHP code
$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
PHP code
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 "; (fblww-0112)
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service