【发布时间】:2011-09-07 21:52:49
【问题描述】:
PHP 的 token_get_all 函数(允许将 PHP 源代码转换为标记)可能会引发两个错误:一个是遇到未终止的多行注释,另一个是发现意外的字符。
我想捕获这些错误并将它们作为异常抛出。
问题是:由于这些错误是解析错误,它们无法使用通常使用set_error_handler 指定的错误处理函数来处理。
我目前实现的如下:
// Reset the error message in error_get_last()
@$errorGetLastResetUndefinedVariable;
$this->tokens = @token_get_all($code);
$error = error_get_last();
if (preg_match(
'~^(Unterminated comment) starting line ([0-9]+)$~',
$error['message'],
$matches
)
) {
throw new ParseErrorException($matches[1], $matches[2]);
}
if (preg_match(
'~^(Unexpected character in input:\s+\'(.)\' \(ASCII=[0-9]+\))~s',
$error['message'],
$matches
)
) {
throw new ParseErrorException($matches[1]);
}
很明显,我对使用该解决方案并不感到兴奋。尤其是我通过访问未定义的变量来重置error_get_last 中的错误消息这一事实似乎非常不令人满意。
那么:这个问题有更好的解决方案吗?
【问题讨论】:
标签: php error-handling tokenize