如何在类内设置函数默认参数


How to set function default parameter inside class?

如何在类内设置函数默认参数?

class tag_0_model {
  protected $response_message;
  public function __construct() {    
    $this->response_message = array(
      "debug_message" => $debug_message =array(),
      "error_message" => $error_message =array(),
      "success_message" => $success_message =array(),
      "warning_message" => $warning_message =array()
    );
  }
  // sure this is parse error , not work
  public function insert_ignore($response_message = $this->response_message, $data) {
    //
  }

我试着像一样使用

class tag_0_controller {
  protected $response_message;
  public function __construct() {    
    $this->response_message = array(
      "debug_message" => $debug_message =array(),
      "error_message" => $error_message =array(),
      "success_message" => $success_message =array(),
      "warning_message" => $warning_message =array()
    );
  }
  public function method() {

    $data = ...;
    $this->tag_0_model->insert_ignore($data);

    // or  

    $response_message = $this->response_message;
    $data = ...;
    $this->tag_0_model->insert_ignore($response_message, $data);
  }
}

1/您不能将所需参数放在可选参数之后,您的"insert_ignore"函数定义应该具有"$data"的默认值

2/您不能将您的属性作为默认参数vlaue。默认参数必须在编译时存在,所以它必须是常量或类常量,我建议您将默认值设置为"null",并从函数内部替换它:

public function insert_ignore($data = array(), $response_message = null)
{
    if( $response_message === null ) {
        $response_message = $this->response_message;
    }
    // ...
}
// Call this function by
$this->tag_0_model->insert_ignore($data);

编辑更新代码