日記
PHP 4にthrow〜catchを載せてみる実験 (10:07)Edit

あらかじめ断っておきますが、単なる実験で実用レベルではないです。

if (!class_exists('exception')) {
function throw($ex)
{
$ex->doCatch();
}
function __catch($ex)
{
die($ex->toString() . "\n" .$ex->getTraceAsString());
}
class Exception
{
var $message = 'Unknown exception';
var $code = 0;
var $file;
var $line;
var $_catchFunction;
var $_trace;
function Exception($catchFunction = '__catch', $message = NULL, $code = 0)
{
$this->_catchFunction = $catchFunction;
$this->message = isset($message) ? $message : $this->message;
$this->code = ($code > 0) ? $code : $this->code;
$this->_trace = debug_backtrace();
$this->file = $this->_trace[0]['file'];
$this->line = $this->_trace[0]['line'];
}
function getMessage()
{
return $this->message;
}
function getCode()
{
return $this->code;
}
function getFile()
{
return $this->file;
}
function getLine()
{
return $this->line;
}
function getTrace()
{
return $this->_trace;
}
function getTraceAsString()
{
return var_export($this->_trace, TRUE);
}
function toString()
{
return "Exception: Code: {$this->code}: {$this->message} in {$this->file} on line {$this->line}";
}
function doCatch()
{
call_user_func($this->_catchFunction, $this);
}
}
}

これで、

throw(new Exception());

とかやると、デフォルトではその時点でのトレースが出力される。

function myCatch($ex)
{
//独自のキャッチ処理
}
throw new Exception('myCatch');

とかやると、独自のキャッチ処理が呼ばれるようになる。

でも強引に指定した関数 or メソッドを呼ばせたところで、関数ならばスコープが別になっちゃうからまっとうな継続処理はできない。メソッドを指定すればインスタンス変数までは一応見えるけど、それでも制約が大きい。

というか、catch処理が終了したあとにthrowの次の行にしか戻れないんで、たいていの場合はcatch処理のあとそのまま終了するしかないのが致命的。結局のところ、trigger_errorを一見例外処理風に書いて見せているだけにすぎない。

exit 2みたいにreturn 2とかやって、関数の呼び出し元の呼び出し元まで脱出できれば、まだ使い出がありそうなんだけど。

というわけで、ただの実験でした。特に実用性はありません。PHP 4でthrow new Exception()と書いてみたかっただけです。

Published At2005-04-13 00:00Updated At2005-04-13 00:00