2013-02-18 40 views
1

因此,我再次閱讀了PHP手冊,並且看到了一個自定義異常的代碼的註釋,以調用父異常構造函數,並且不理解此目的。異常類中的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"; 
    } 
} 

我不明白的邏輯「//確保一切正確分配父:: __構造($消息,$代碼);」

任何邏輯,爲什麼這樣做會有所幫助。

回答

1

當您覆蓋構造函數方法時,PHP將不會自動調用父類的構造方法。因此,如果父級的構造函數仍然是必需的,則必須手動調用它。

0

以及PHP的基礎異常類將消息/代碼分配給某些內部屬性。 我敢肯定,這個類的作者可能沒有編寫_ construct();但在這種情況下,他想證明該父項:: _construct();必須在覆蓋構造函數時調用。

1

Exception類包含自己的屬性,如$code$message

它們是由子類,例如ihnerited:

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. 
    } 
} 

所以,你叫後parent::__construct()

你的子類必須實例變量$code$message設置正確。

$myEx = new MyException("10", "DB Error") ; 
//Now you can get the error code, because it was set in its parent constructor: 
$code = $myEx->getCode() ;