2

于是又在看PHP手册,看到一个自定义异常调用父异常构造函数的代码的注释,不明白这样做的目的。

这是代码:

class MyException extends Exception
{
        // Redefine the exception so message isn't optional
        public function __construct($message, $code = 0) {
        // some code

        // make sure everything is assigned properly
        parent::__construct($message, $code);
    }

    // custom string representation of object
    public function __toString() {
    return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }

    public function customFunction() {
        echo "A custom function for this type of exception\n";
    }
}

我不明白以下逻辑:

//make sure everything is assigned properly
parent::__construct($message, $code);

关于为什么这样做的任何逻辑都会有所帮助。

4

3 回答 3

2

Exception class contains own properties such as $code and $message

They are ihnerited by child classes, example:

class Exception {
  protected $code ;
  protected $message ;

  public function __construct($code, $message){
    $this->code = $code ;
    $this->message = $message ;

    //AND some important default actions are performed
    //when class is instantiated.
  }
}

So, after you called parent::__construct()

Your child class will have instance variables $code and $message set properly.

$myEx = new MyException("10", "DB Error") ;
//Now you can get the error code, because it was set in its parent constructor:
$code = $myEx->getCode() ;
于 2013-02-18T13:40:54.923 回答
1

当你重写构造方法时,PHP 不会自动调用父类的构造方法。所以如果仍然需要父的构造函数,你必须手动调用它。

于 2013-02-18T13:39:04.953 回答
0

PHP的基本异常类将消息/代码分配给一些内部属性。我敢肯定这个类的作者可能没有写 _construct (); 但在这种情况下,他想证明 parent:: _construct(); 如果您覆盖构造函数,则必须调用。

于 2013-02-18T13:39:29.760 回答