我在命名函数时遇到了问题。我有一个类,我需要两个函数,如下所示。
class myclass {
public function tempclass () {
echo "default";
}
public function tempclass ( $text ) {
echo $text;
}
}当我打电话的时候
tempclass('testing'); // ( called after creating the object )function tempclass()正在被调用,我怎么才能有两个同名不同参数的函数呢?
发布于 2012-04-20 23:22:48
传统的重载目前在PHP中是不可能的。相反,您需要检查传递的参数,并确定您希望如何响应。
在这里查看func_num_args和func_get_args。您可以在内部使用这两种方法来确定应该如何响应对某些方法的调用。例如,在您的示例中,您可以执行以下操作:
public function tempclass () {
switch ( func_num_args() ) {
case 0:
/* Do something */
break;
case 1:
/* Do something else */
}
}或者,您也可以为您的参数提供默认值,并使用这些值来确定您应该如何反应:
public function tempclass ( $text = false ) {
if ( $text ) {
/* This method was provided with text */
} else {
/* This method was not invoked with text */
}
}发布于 2012-04-20 23:25:26
重载在PHP中是不可能的。
但是,对于上面的简单示例,如下所示将会起作用:
class myclass {
public function tempclass ($text='Default') {
echo $text;
}
}https://stackoverflow.com/questions/10248961
复制相似问题