新聞中心

PHP 中屏蔽錯誤的方法有 3 中,下面就來分別介紹一下。
1、使用錯誤控制運算符:@
PHP 支持使用錯誤控制運算符
@。將其放置在一個 PHP 表達式之前,該表達式可能產(chǎn)生的任何錯誤信息都將被忽略掉。
如果用 set_error_handler() 設定了自定義的錯誤處理函數(shù),這個錯誤處理函數(shù)仍然會被調(diào)用,而如果在出錯語句前使用了
@ 的話,錯誤處理函數(shù)將返回 0。
需要注意的是,
@ 運算符只對表達式有效。簡單來說就是,如果能從某處得到值,就能在它前面加上 @ 運算符。例如可以在變量、函數(shù)、include 調(diào)用、常量等等之前使用 @ 運算符,但不能把它放在函數(shù)或類的定義之前,也不能用于條件結(jié)構(gòu)例如 if 和 foreach 等語句前。
@ 運算符對于可以導致程序終止的嚴重錯誤也是有效的,這意味著如果在某個不存在或者敲錯了字母的函數(shù)調(diào)用前用了
@ 來抑制錯誤信息,那么程序?qū)]有任何提示的死在那里。
【示例】使用 @ 錯誤控制運算符屏蔽代碼中的錯誤。
運行結(jié)果如下:
數(shù)據(jù)庫連接失??!
2、使用 error_reporting() 函數(shù)屏蔽錯誤
PHP 有諸多錯誤級別,使用 error_reporting() 函數(shù)可以設置 PHP 會報告何種錯誤,函數(shù)的語法格式如下:
error_reporting([int $level])
其中參數(shù) $level 為設置錯誤級別,具體可以使用的值可以在《PHP錯誤級別》一節(jié)中查看。如果將 $level 設置為 0,將關閉所有 PHP 錯誤報告;如果設置為 -1,將返回所有的錯誤報告。
【示例】使用 error_reporting() 函數(shù)屏蔽代碼中的錯誤。
3、通過 display_errors 參數(shù)屏蔽錯誤
這種方法應該是最徹底的一種解決辦法,因為前兩種方法只能作用于單行或者單個文件,而這個則是作用于所有的 PHP 文件。
具體的操作方法就是,打開 php.ini 配置文件,在其中搜索 display_errors,然后將 display_errors 的值設置為 Off 即可關閉所有的 PHP 錯誤報告。如下所示:
; This directive controls whether or not and where PHP will output errors,
; notices and warnings too. Error output is very useful during development, but
; it could be very dangerous in production environments. Depending on the code
; which is triggering the error, sensitive information could potentially leak
; out of your application such as database usernames and passwords or worse.
; For production environments, we recommend logging errors rather than
; sending them to STDOUT.
; Possible Values:
; Off = Do not display any errors
; stderr = Display errors to STDERR (affects only CGI/CLI binaries!)
; On or stdout = Display errors to STDOUT
; Default Value: On
; Development Value: On
; Production Value: Off
; http://php.net/display-errors
display_errors = Off
網(wǎng)站標題:PHP屏蔽錯誤
標題路徑:http://m.5511xx.com/article/djpjgsj.html


咨詢
建站咨詢
