我最近一直在询问有关异常和处理异常等问题,which as recently best explained to me in this question.我现在的问题是如何使用
set_exception_handler();
在类中设置php中的错误处理类,当抛出错误时,由此类处理。正如定义所述:
如果未在try / catch块中捕获异常,则设置默认异常处理程序。调用exception_handler后执行将停止。
我以为我可以这样做:
class Test{
public function __construct(){
set_exception_handler('exception');
}
public function exception($exception){
echo $exception->getMessage();
}
}
但问题是,如果用户正在设置应用程序或使用应用程序中的任何API,则必须执行整个操作:new Test();
那么我怎么能编写一个异常处理程序类:
我所展示的方式是我能想到的唯一方法。
答案 0 :(得分:9)
每个人都认为使用set_exception_handler会捕获PHP中的所有错误,但事实并非如此,因为set_exception_handler没有处理某些错误,处理所有类型错误的正确方法必须按以下方式完成:
//Setting for the PHP Error Handler
set_error_handler( call_back function or class );
//Setting for the PHP Exceptions Error Handler
set_exception_handler(call_back function or class);
//Setting for the PHP Fatal Error
register_shutdown_function(call_back function or class);
通过设置这三个设置,您可以捕获PHP的所有错误。
答案 1 :(得分:8)
为了让您的班级工作,您的构造函数中的行应该是:
// if you want a normal method
set_exception_handler(array($this, 'exception'));
// if you want a static method (add "static" to your handler method
set_exception_handler(array('Test', 'exception'));