php - PHP 中的 trigger_error() 是否因为 PHP5 中更好的东西而被弃用?

标签 php error-handling

当我想在 PHP 中触发错误时,我曾经使用它,来自 PHP4 背景。请注意,我有自己的 set_error_handler() 来处理这些错误。

if ($error) {
    trigger_error('Sorry, error has occured');
}

我不记得在哪里,但前段时间有人告诉我应该“使用异常”。由于我正在重构我的很多旧代码,我想现在是时候就我的错误处理实现获得一些好的建议了。

现在我正在使用 PHP5(并且比我编写旧代码时更聪明),我的 trigger_error() 是否只是一种旧的处理方式,如果是这样,在 PHP5 中处理错误的最佳方法是什么?

最佳答案

是的,您可能想开始研究 PHP 5 异常模型。请记住,仅仅因为某些东西是新的并不意味着您必须采用它。仅采用您需要且在您的域中有意义的那些功能。

话虽如此,我觉得异常是一个很好掌握的概念,即使您决定不采用它们,您的体验也会更好。

我建议您阅读 PHP: Exceptions - Manual :

PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exeptions. Normal execution (when no exception is thrown within the try block, or when a catch matching the thrown exception's class is not present) will continue after that last catch block defined in sequence. Exceptions can be thrown (or re-thrown) within a catch block.

我也鼓励您阅读 What Is an Exception? (请注意,这是一个 Java 教程,但概念是通用的)

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

编辑:为了实现一个全局异常处理程序(基本上是为了建立一个默认的异常处理程序来处理以前未处理的异常),您需要我们 set_exception_handler功能。

关于php - PHP 中的 trigger_error() 是否因为 PHP5 中更好的东西而被弃用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/770694/

相关文章:

C# 嵌套 Try Catch 语句或方法?

php - 使用路径文件夹回显数据库中的图像,

javascript - 仅向来自特定引荐来源网址的访问者显示页面中的 iframe

php - 将数据保存在mysql中并向订阅者发送邮件。如何解决?

php - Composer 将文件安装到哪里?

ios - 将 NSObject 转换为 RLMObject 以将其保存到 Realm 数据库

php - Laravel 处理异常

c# - 如何将多个错误传递给 ReplaySubject?

java - 在JSP中导入类时出错

php 日期未发布在数据库表中