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函数.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...