实际上 PHP 确实支持函数重载,但方式不同。 PHP 的 overloading features 与 Java 不同:
PHP 对“重载”的解释与大多数面向对象的语言不同。传统上,重载提供了拥有多个具有相同名称但参数数量和类型不同的方法的能力。
检查以下代码块。
求n个数之和的函数:
function findSum() {
$sum = 0;
foreach (func_get_args() as $arg) {
$sum += $arg;
}
return $sum;
}
echo findSum(1, 2), '<br />'; //outputs 3
echo findSum(10, 2, 100), '<br />'; //outputs 112
echo findSum(10, 22, 0.5, 0.75, 12.50), '<br />'; //outputs 45.75
Function to add two numbers or to concatenate two strings:
function add() {
//cross check for exactly two parameters passed
//while calling this function
if (func_num_args() != 2) {
trigger_error('Expecting two arguments', E_USER_ERROR);
}
//getting two arguments
$args = func_get_args();
$arg1 = $args[0];
$arg2 = $args[1];
//check whether they are integers
if (is_int($arg1) && is_int($arg2)) {
//return sum of two numbers
return $arg1 + $arg2;
}
//check whether they are strings
if (is_string($arg1) && is_string($arg2)) {
//return concatenated string
return $arg1 . ' ' . $arg2;
}
trigger_error('Incorrect parameters passed', E_USER_ERROR);
}
echo add(10, 15), '<br />'; //outputs 25
echo add("Hello", "World"), '<br />'; //outputs Hello World
面向对象的方法,包括方法重载:
PHP 中的重载提供了动态“创建”属性和方法的方法。这些动态实体是通过可以在一个类中为各种动作类型建立的魔术方法进行处理的。
参考:http://php.net/manual/en/language.oop5.overloading.php
在 PHP 中,重载意味着您可以在运行时添加对象成员,方法是实现一些魔术方法,例如 __set、__get、__call 等。
类 Foo {
public function __call($method, $args) {
if ($method === 'findSum') {
echo 'Sum is calculated to ' . $this->_getSum($args);
} else {
echo "Called method $method";
}
}
private function _getSum($args) {
$sum = 0;
foreach ($args as $arg) {
$sum += $arg;
}
return $sum;
}
}
$foo = new Foo;
$foo->bar1(); // Called method bar1
$foo->bar2(); // Called method bar2
$foo->findSum(10, 50, 30); //Sum is calculated to 90
$foo->findSum(10.75, 101); //Sum is calculated to 111.75