Neo Inspiration

Feed Rss

set_error_handler と restore_error_handler

01.14.2010, PHP, by .

シングルトン君を書いてる時にふと
try-catchのとこをきれいにかけないかなと思って
(今までいちいちtry文の中で throw new Exception() してたので)
set_error_handlerを使って書き直してみました。

//今までこんなかんじでめんどくさい
public function hogehoge() {
    try {
        if (TRUE === $error) {
            throw new Exception($e);
        }
        if (~~~) {
            throw new Exception($e);
        }
    } catch(Exception $e) {

    }
}

//set_error_handlerを使うとこうなる
public function hogehoge() {
    set_error_handler("Class名::dbErrorHandler");
    try {

    } catch(Exception $e) {

    }
    restore_error_handler();
}

public static function dbErrorHandler($enNo,$eStr,$eFile,$eLine) {
    throw new Exception($eStr,$enNo);
}

おーやっとそれっぽくなった。

ちなみに set_error_handler() は staticで書いておけば

set_error_handler("クラス名::dbErrorHandler");
set_error_handler("self::dbErrorHandler");
set_error_handler(array($this,'dbErrorHandler');

のどれでもいけます。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

*

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>