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の基本のExceptionクラスは、メッセージ/コードをいくつかの内部プロパティに割り当てます。このクラスの作成者は_construct ();を記述できなかったと思います。しかし、この場合、彼はその親を示したかった:: _construct(); コンストラクターを上書きする場合は呼び出す必要があります。

于 2013-02-18T13:39:29.760 に答える