在Java中,我们有一个方法重载特性,它对Singleton非常有用。例如,我有两个不同的getInstance方法,public static,它们根据接收到的参数表现不同:
public static Currency getInstance(String currencyCode)
public static Currency getInstance(Locale locale)
我们可以用PHP做这件事吗?
您可以在运行时确定参数类型:
function getInstance($currency) {
if (is_string($currency)) {
$currency = lookupLokale($currency);
}
// do something with the $currency object
}
在php5.3+(非静态方法为php5.0+(中,您还可以使用php的方法重载来自己实现类似Java的语义。然而,OOP重载可能会产生混乱的代码,您应该更喜欢方法解决方案中的上述内容。
在大多数情况下,如果只使用两个不同的方法名,会更清楚。
来吧,至少试试谷歌:(。这方面有很好的文档。例如,在PHP网站ITSELF:上
EDIT:描述方法重载的新链接
http://www.dinke.net/blog/en/2007/08/01/method-overloading-in-php5/
现在我也遇到了同样的过载。
直接PHP不支持方法重载,但我们可以使用func_get_args((实现此功能:
class Obj
{
function __construct() {
$args = func_get_args();
if (count($args) != 2) {
echo ("Must be passed two arguments !'n");
return;
}
if (is_numeric($args[0]) && is_numeric($args[1])) {
$result = $this->_addnum($args[0], $args[1]);
}
else if (is_string($args[0]) && is_string($args[1])) {
$result = $this->_addstring($args[0], $args[1]);
}
else if (is_bool($args[0]) && is_bool($args[1])) {
$result = $this->_addbool($args[0], $args[1]);
}
else if (is_array($args[0]) && is_array($args[1])) {
$result = $this->_addarray($args[0], $args[1]);
}
else {
echo ("Argument(s) type is not supported !'n");
return;
}
echo "'n";
var_dump($result);
}
private function _addnum($x, $y) {return $x + $y;}
private function _addstring($x, $y) {return $x . $y;}
private function _addbool($x, $y) {return $x xor $y;}
private function _addarray($x, $y) {return array_merge($x,$y);}
}
// invalid constructor cases
new Obj();
new Obj(null, null);
// valid ones
new Obj(2,3);
new Obj('A','B');
new Obj(false, true);
new Obj([3], [4]);
输出:
必须传递两个参数!不支持参数类型!int(5(字符串(2("AB"布尔(真(阵列(2({[0]=>int(3([1] =>int(4(}