在php中创建一个错误处理程序类

The*_*ebs 3 php error-handling exception

我最近一直在询问有关异常和处理异常等问题,最近我在这个问题上最好地解释了这个问题.我现在的问题是如何使用

set_exception_handler();
Run Code Online (Sandbox Code Playgroud)

在一个类中设置php中的错误处理类,当抛出错误时,由此类处理.正如定义所述:

如果未在try/catch块中捕获异常,则设置缺省异常处理程序.调用exception_handler后,执行将停止.

我以为我可以这样做:

class Test{
    public function __construct(){
        set_exception_handler('exception');
    }

    public function exception($exception){
        echo $exception->getMessage();
    }
}
Run Code Online (Sandbox Code Playgroud)

但问题是,如果用户正在设置应用程序或使用应用程序中的任何API,则必须执行以下操作: new Test();

那么我怎么能编写一个异常处理程序类:

  1. 抛出异常时自动调用以处理"未捕获"异常.
  2. 以可扩展的OOP方式完成.

我展示的方式是我能想到的唯一方法.

Vin*_*982 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);
Run Code Online (Sandbox Code Playgroud)

通过设置这三个设置,您可以捕获PHP的所有错误.


SE *_*lio 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'));
Run Code Online (Sandbox Code Playgroud)

  • 值得一提的是,通常,当您想要将函数名称传递给某个函数并且该函数实际上是一个对象方法时,您可以使用此处显示的语法.也就是说,此解决方案适用于其他期望函数名称的PHP方法. (2认同)
  • 我知道这是很久以前的事了,但最好使用 `static::class` 而不是静态方法的类名。通过使用它,您可以支持命名空间。`set_exception_handler(array(static::class, 'exception'));` (2认同)