<?php
/**
* 自定義一個異常處理類
*/
class MyException extends Exception
{
// 重定義構造器使 message 變為必須被指定的屬性
public function __construct($message, $code = 0) {
// 自定義的代碼
// 確定所有變量都被正确指派
parent::__construct($message, $code);
}
// 自定義字元串輸出的樣式
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
/**
* 建立一個用于測試異常處理機制的類
*/
class TestException
{
function __construct($str) {
if($str == 1)
throw new MyException('參數不能為1哦',1);
elseif($str == 2)
throw new MyException('參數不能為2哦',2);//抛出2個異常
else
echo $str;
}
}
try {
$o = new TestException(2);
} catch (MyException $e) { // 捕獲異常
echo $e;
}
?>