function getCommandObject($cmd) {
$path = "{$this->cmdDir}/{$cmd}.php";
if (!file_exists($path)) {
throw new Exception("Cannot find $path");
}
require_once $path;
if (!class_exists($cmd)) {
throw new Exception("class $cmd does not exist");
}
$class = new ReflectionClass($cmd);
if (!$class->isSubclassOf(new ReflectionClass('Command'))) {
throw new Exception("$cmd is not a Command");
}
return new $cmd();
}
}
?>
代碼中我們使用了PHP5的反射(Reflection)API來判斷所給的類是否是屬於Command 類型。在錯誤的路徑下執行本指令碼將會報出這樣的錯誤:
Fatal error: Uncaught exception 'Exception' with message 'Cannot find command/xrealcommand.php' in /home/xyz/BasicException.php:10
Stack trace:
#0 /home/xyz/BasicException.php(26):
CommandManager->getCommandObject('xrealcommand')
#1 {main}
thrown in /home/xyz/BasicException.php on line 10
預設地,拋出異常導致一個fatal error。這意味著使用異常的類內建有安全機制。而僅僅使用一個錯誤標記,不能擁有這樣的功能。處理錯誤標記失敗只會你的指令碼使用錯誤的值來繼續執行。