【问题标题】:How to throw a Not Implemented Error [duplicate]如何抛出未实现的错误[重复]
【发布时间】:2012-10-19 22:23:30
【问题描述】:

可能重复:
Throw a NotImplementedError in PHP?

在编写基类时,我经常逐步开发,只构建我需要的(或者,我正在测试的)。然而我喜欢我的界面是平衡的。对于每个 getter 一个 setter。在实现 CRUD 时,即使现在我只需要 R,我宁愿为 CUD 编写存根。

我希望这些抛出一些未实现的异常。如何引发此类错误或异常?

例如:

class Resource {
  /**
   * get Issues a GET-request to Online, fetch with $this::$id
   * @returns $this
   */
  protected function get() {
    if ($this->id) {
      $attributes = http_build_query(array("id" => $this->id));
      $url = "{$this->url}?{$attributes}";
      $options = array_merge(array('method' => 'GET'));
      $response = _http_request($url, $options);
      $this->parse($response);
    }
    return $this;
  }

  /**
   * post Place a new object on Online
   *
   * @param $attributes ....
   * @returns Source $this
   */
  protected function post($attributes = array()) {
    throw new NotImplementedError();
  }

  /**
   * put Updates an object on Online
   *
   * @param $attributes ....
   * @returns $this
   */
  protected function put($attributes = array()) {
    throw new NotImplementedError();
  }

  /**
   * delete Removes an object from Online, selected by $this::$id.
   * @returns $this
   */
  protected function delete() {
    throw new NotImplementedError();
  }
}

【问题讨论】:

  • 是的。它是重复的。问题是搜索“未实现的错误 PHP”会给出数百页关于某些库或类抛出该错误的问题。即:我搜索了,但没有找到。谢谢。

标签: php error-handling


【解决方案1】:

您可以 throw new NotImplementedException() - 就像 Symfony API 中的 this one

【讨论】:

    【解决方案2】:

    看看这个之前的回答:Throw a NotImplementedError in PHP?

    简单地说,PHP 中不存在异常,但您可以通过扩展现有异常轻松创建自己的异常。上一个答案建议使用 BadMethodCallException 来执行此操作:

    class NotImplementedException extends BadMethodCallException
    {}
    

    然后你可以在你的代码中抛出一个 NotImplementedException。

    【讨论】:

      【解决方案3】:

      在我看来,您有两种可能性:

      1. 从异常类派生并实现一个not implemented exception,您可以抛出它。
      2. 将未实现的方法定义为抽象。然后编译器会产生一个错误。不要忘记将整个基类标记为抽象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-20
        • 2021-03-26
        • 2021-10-14
        相关资源
        最近更新 更多