php:自动加载异常处理

php:自动加载异常处理,php,exception-handling,autoload,Php,Exception Handling,Autoload,我扩展了我前面的问题(在异常句柄中处理异常),以解决我糟糕的编码实践。 我正在尝试将自动加载错误委托给异常处理程序 <?php function __autoload($class_name) { $file = $class_name.'.php'; try { if (file_exists($file)) { include $file; }else{ throw new loadEx

我扩展了我前面的问题(在异常句柄中处理异常),以解决我糟糕的编码实践。 我正在尝试将自动加载错误委托给异常处理程序

<?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块,所以我尝试了这个方法


处理此问题的正确方法是什么?

您是否尝试过在过程的早期检查
pageClass
,因为即使要将错误页面取出,也似乎是必要的?如果它不存在,并且如果您不想编写404页而不包含任何对象(例如,仅HTML),那么在该类不存在的地方停止执行似乎是一个好方法

希望有帮助

谢谢,

我只是要求事先上课