PHP类函数命名

Abh*_*ian 2 php naming class function

我在命名函数时遇到问题.我有一个课,我需要2个功能,如下所示.

class myclass {
    public function tempclass () {
        echo "default";   
    }
    public function tempclass ( $text ) {
        echo $text;
    }
}
Run Code Online (Sandbox Code Playgroud)

我打电话的时候

tempclass('testing'); // ( called after creating the object )
Run Code Online (Sandbox Code Playgroud)

function tempclass() 正在被称为我有两个具有相同名称但不同参数的功能?

Sam*_*son 5

PHP目前无法实现传统的重载.相反,您需要检查传递的参数,并确定您希望如何响应.

退房func_num_args,并func_get_args在这一点上.您可以在内部使用这两个来确定如何响应某些方法的调用.例如,在您的情况下,您可以执行以下操作:

public function tempclass () {
  switch ( func_num_args() ) {
    case 0:
      /* Do something */
      break;
    case 1:
      /* Do something else */
  }
}
Run Code Online (Sandbox Code Playgroud)

或者,您也可以为参数提供默认值,并使用它们来确定您应该如何反应:

public function tempclass ( $text = false ) {
  if ( $text ) {
    /* This method was provided with text */ 
  } else {
    /* This method was not invoked with text */
  }
}
Run Code Online (Sandbox Code Playgroud)