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

时间:2014-11-12 03:43:07

标签: php parameters default-value

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

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 个答案:

答案 0 :(得分:1)

1 /你不能在optionnal参数之后输入所需的参数,你的" 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);

编辑更新了代码