gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 23:54:16 26 4
gpt4 key购买 nike

我最近一直在问异常和处理异常等问题,which as recently best explained to me in this question.我现在的问题是我将如何使用

set_exception_handler();

在一个类中设置一个错误处理类,在php中,当有错误被抛出时,由这个类来处理。正如定义所述:

Sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the exception_handler is called.

我在想我可以做这样的事情:

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

public function exception($exception){
echo $exception->getMessage();
}
}

但问题是,如果用户正在设置应用程序或使用应用程序中的任何 API,他们必须做一个整体:new Test();

那么我如何编写一个异常处理程序类:

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

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

最佳答案

为了让你的类(class)正常工作,你的构造函数中的行应该是:

// 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'));

关于php - 在 php 中创建错误处理程序类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14950267/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com