【问题标题】:How to set function default parameter inside class?如何在类内设置函数默认参数?
【发布时间】:2015-01-08 19:51:41
【问题描述】:

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

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) {
    //
  }

我尝试使用like

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);
  }
}

【问题讨论】:

  • 您有没有遇到任何错误?问题不清楚。
  • 编辑并添加错误。
  • 参数不能是类的属性,你必须设置一个像$response_message=array()这样的变量
  • @miglio 感谢您的回复,我尝试让 response_message isset 或 not isset 使用默认数组,但正如您所见,如果我写入参数,response_message 属性很长,难以阅读,有什么办法可以做某事

标签: php parameters default-value


【解决方案1】:

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);

编辑更新代码

【讨论】:

  • 感谢您的回复,所以我可以使用 $this->tag_0_model->insert_ignore($data);将第一个 response_message 参数留空?
  • 应该是:$this->tag_0_model->insert_ignore(null, $data);或者你可以改变参数顺序: public function insert_ignore($data = array(), $response_message = null) 然后调用它使用: $this->tag_0_model->insert_ignore($data); (我已经更新了我的答案)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-06
  • 1970-01-01
  • 2013-01-01
  • 2010-10-22
  • 2013-01-16
  • 2019-11-02
  • 2010-10-28
相关资源
最近更新 更多