2

以前の質問 (例外ハンドル内で例外を処理する) を拡張して、私の悪いコーディング プラクティスに対処します。オートロード エラーを例外ハンドラに委譲しようとしています。

<?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 ブロックを追加したくないので、これを試しました。

これを処理する適切な方法は何ですか?

4

1 に答える 1

1

pageClassエラーページを出すためにも必要なようですので、早い段階でチェックしてみてはいかがでしょうか。それが存在せず、オブジェクトなしで 404 ページ (たとえば HTML のみ) を書きたくない場合は、そのクラスが存在しない場所で実行を爆破するのが良い方法のようです。

それが役立つことを願っています。

ありがとう、ジョー

于 2010-05-13T13:19:40.617 に答える