我将扩展我以前的问题(在异常处理中处理异常),以解决我的错误编码实践。
我正在尝试将自动加载错误委托给异常处理程序。
<?php
function __autoload($class_name) {
$file = $class_name.'.php';
try {
if (file_exists($file)) {
include $file;
}else{
throw new loadException("File $file is missing");
}
if(!class_exists($class_name,false)){
throw new loadException("Class $class_name missing in $file");
}
}catch(loadException $e){
header("HTTP/1.0 500 Internal Server Error");
$e->loadErrorPage('500');
exit;
}
return true;
}
class loadException extends Exception {
public function __toString()
{
return get_class($this) . " in {$this->file}({$this->line})".PHP_EOL
."'{$this->message}'".PHP_EOL
. "{$this->getTraceAsString()}";
}
public function loadErrorPage($code){
try {
$page = new pageClass();
echo $page->showPage($code);
}catch(Exception $e){
echo 'fatal error: ', $code;
}
}
}
$test = new testClass();
?>
如果testclass.php文件丢失,那么上面的脚本应该加载404页,并且它工作正常,除非pageclass.php文件也丢失,在这种情况下,我看到
“致命错误:在第29行的d:\xampp\htdocs\test\php\errorhandle\index.php中找不到类”pageclass“,而不是“致命错误:500”消息
我不想向每个类自动加载(对象创建)添加一个try/catch块,所以我尝试了这个方法。
正确的处理方法是什么?