我正在扩展我之前的问题(在异常句柄中处理异常)以解决我糟糕的编码习惯。我正在尝试将自动加载错误委托给异常处理程序。
<?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 块,所以我尝试了这个。
处理这个的正确方法是什么?