微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PHP中的trigger_error()是否因PHP5中的某些内容而被弃用?

当我想在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函数.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐