PHP 基礎篇 - PHP 錯誤級別詳解
阿新 • • 發佈:2017-12-26
ice 詳細介紹 arch fatal star use tom int error
一、前言
最近經常看到工作 2 年左右的童鞋寫的代碼也會出現以靜態方法的形式調用非靜態方法,這是個 Deprecated
級別的語法錯誤,代碼裏不應該出現的。對方很郁悶,說:為什麽我的環境可以正常運行呢?
二、詳解
代碼會不會報錯,以及你能不能看到報錯信息由 PHP 配置中以下兩個參數影響,目前線上主流的配置如下(php.ini 文件中):
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
display_errors = Off
下面詳細介紹這兩個參數:
1. error_reporting
首先來說說 PHP 的錯誤級別,代碼會不會報錯由 error_reporting 參數決定,PHP 的錯誤級別種類如下(點擊查看中文版):
E_ALL - All errors and warnings (includes E_STRICT as of PHP 5.4.0) E_ERROR - fatal run-time errors E_RECOVERABLE_ERROR - almost fatal run-time errors E_WARNING - run-time warnings (non-fatal errors) E_PARSE - compile-time parse errors E_NOTICE - run-time notices (these are warnings which often result from a bug in your code, but it‘s possible that it was intentional (e.g., using an uninitialized variable and relying on the fact it is automatically initialized to an empty string) E_STRICT - run-time notices, enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code E_CORE_ERROR - fatal errors that occur during PHP‘s initial startup E_CORE_WARNING - warnings (non-fatal errors) that occur during PHP‘s initial startup E_COMPILE_ERROR - fatal compile-time errors E_COMPILE_WARNING - compile-time warnings (non-fatal errors) E_USER_ERROR - user-generated error message E_USER_WARNING - user-generated warning message E_USER_NOTICE - user-generated notice message E_DEPRECATED - warn about code that will not work in future versions of PHP E_USER_DEPRECATED - user-generated deprecation warnings
其中 WARNING、NOTICE、DEPRECATED 等錯誤級別會拋出一個錯誤,但不會終止程序運行。
2. display_errors
再來看一下 display_errors 參數,該參數是是否展示錯誤信息,只有開啟才會顯示錯誤信息(值可以為 on|off、true|false、1|0)。
開發環境最好設置為開啟,盡早發現問題,但生產環境一定要關閉。(點擊查看中文版官方文檔)
3. 問題演示
下面使用 PHP 的運行時配置,改變 PHP 的 error_reporting 和 display_errors,演示上面的問題。代碼如下:
<?php // error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT); // 該級別下面的代碼不會拋出錯誤 error_reporting(E_ALL & ~E_NOTICE); ini_set("display_errors", "on"); class Foo { public function test() { echo ‘test‘; } } Foo::test();
運行該代碼會輸出 test
,但同時會拋出一個 Deprecated
級別的錯誤。這種情況應該杜絕,規範開發,從基礎做起,人人有責!
本文首發於馬燕龍個人博客,歡迎分享,轉載請標明出處。
馬燕龍個人博客:http://www.mayanlong.com
馬燕龍個人微博:http://weibo.com/imayanlong
馬燕龍Github主頁:https://github.com/yanlongma
PHP 基礎篇 - PHP 錯誤級別詳解