【发布时间】:2013-07-23 02:08:47
【问题描述】:
在我的 PHP 编程生涯中,每当我在 PHP 中创建具有相同名称但参数不同的函数时,都会导致错误。因此,我想知道 PHP 是否有任何类型的函数重载功能,如果有,我会很感激给我一个例子。
谢谢。
【问题讨论】:
-
是的,它是重复的。这个问题我需要做什么?
标签: php overloading
在我的 PHP 编程生涯中,每当我在 PHP 中创建具有相同名称但参数不同的函数时,都会导致错误。因此,我想知道 PHP 是否有任何类型的函数重载功能,如果有,我会很感激给我一个例子。
谢谢。
【问题讨论】:
标签: php overloading
简单地说:没有。在 PHP 中,方法签名不包括它的参数集,只包括它的名称。因此,两个同名但参数不同的方法实际上被认为是相等的(从而导致错误)。
PHP 确实有一个不同的过程,它称为方法重载,但它是解决问题的不同方法。在 PHP 中,重载是一种可以在运行时在对象上动态创建方法和属性的方法。下面是一个使用__call 方法的示例。
当没有与类内部调用的方法名称匹配的方法时,将调用类的__call 方法。它将接收方法名称和参数数组。
class OverloadTest {
public function __call($method, $arguments) {
if ($method == 'overloadedMethodName') {
switch (count($arguments)) {
case 0:
return $this->overloadedMethodNoArguments();
break;
case 1:
return $this->overloadedMethodOneArgument($arguments[0]);
break;
case 2:
return $this->overloadedMethodTwoArguments($arguments[0], $arguments[1]);
break;
}
}
}
protected function overloadedMethodNoArguments() { print "zero"; }
protected function overloadedMethodOneArgument($one) { print "one"; }
protected function overloadedMethodTwoArguments($one, $two) { print "two"; }
}
$test = new OverloadTest();
$test->overloadedMethodName();
$test->overloadedMethodName(1);
$test->overloadedMethodName(1, 2);
或者,您可以提供一个带有默认参数的函数,这将有效地允许 看起来像 重载的语法。如:
function testFunction($one, $two = null, $three = null) {
}
testFunction(1);
testFunction(1, 2);
testFunction(1, 2, 3);
最后,对于第三种方法,您当然总是可以在函数本身中将参数作为数组访问
function variableFunction() {
$arguments = func_get_args();
switch (count($arguments)) {
// ...
}
}
variableFunction();
variableFunction(1, 2, 3, 4, 5, 6, 7, 8, 9);
【讨论】: