有没有办法显示或抛出 PHP 警告?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1095860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:56:02  来源:igfitidea点击:

Is there any way to show, or throw, a PHP warning?

phpwarnings

提问by igorsantos07

I have a select()method in a database class, that has an optional boolean argument $sum. This argument is used to say if the method should use COUNT(*)or not too.

select()在数据库类中有一个方法,它有一个可选的布尔参数$sum。此参数用于说明该方法是否也应使用COUNT(*)

I would like to show a warning, like those normal PHP errors, if I try to access $class->sumif the attribute is not set (i.e. when I call select()with $sum == false.

我想显示一个警告,像普通的PHP错误,如果我尝试访问$class->sum如果属性未设置(即当我打电话select()$sum == false

Is there any way to show a warning like this, or I should just echo an error and be happy?

有没有办法显示这样的警告,或者我应该只回显错误并感到高兴?

回答by T30

If you want to generate a warning, you should write

如果你想产生一个警告,你应该写

trigger_error($yourErrorMessage, E_USER_WARNING);

trigger_error()has the $error_typeparameter for setting the error level (Notice, Warningor Fatal error). The constants are, respectively:

trigger_error()具有$error_type用于设置错误级别的参数(NoticeWarningFatal error)。常数分别为:

E_USER_NOTICE             // Notice (default)
E_USER_WARNING            // Warning
E_USER_ERROR              // Fatal Error


Note that Fatal errorstops the execution of subsequent PHP code, while Noticeand Warninglet it continue.

请注意,Fatal error停止后续PHP代码的执行,而NoticeWarning让它继续。

From PHP 5.5, you should also consider the Finallystatement.

从 PHP 5.5 开始,您还应该考虑finally语句。

回答by alex

You could try trigger_error().

你可以试试trigger_error()

回答by moo

You're going the object-oriented approach, so I suggest a look into exceptions.

您将采用面向对象的方法,因此我建议您查看异常情况。