新聞中心

PHP 中屏蔽錯(cuò)誤的方法有 3 中,下面就來(lái)分別介紹一下。
1、使用錯(cuò)誤控制運(yùn)算符:@
PHP 支持使用錯(cuò)誤控制運(yùn)算符
@。將其放置在一個(gè) PHP 表達(dá)式之前,該表達(dá)式可能產(chǎn)生的任何錯(cuò)誤信息都將被忽略掉。
如果用 set_error_handler() 設(shè)定了自定義的錯(cuò)誤處理函數(shù),這個(gè)錯(cuò)誤處理函數(shù)仍然會(huì)被調(diào)用,而如果在出錯(cuò)語(yǔ)句前使用了
@ 的話,錯(cuò)誤處理函數(shù)將返回 0。
需要注意的是,
@ 運(yùn)算符只對(duì)表達(dá)式有效。簡(jiǎn)單來(lái)說(shuō)就是,如果能從某處得到值,就能在它前面加上 @ 運(yùn)算符。例如可以在變量、函數(shù)、include 調(diào)用、常量等等之前使用 @ 運(yùn)算符,但不能把它放在函數(shù)或類的定義之前,也不能用于條件結(jié)構(gòu)例如 if 和 foreach 等語(yǔ)句前。
@ 運(yùn)算符對(duì)于可以導(dǎo)致程序終止的嚴(yán)重錯(cuò)誤也是有效的,這意味著如果在某個(gè)不存在或者敲錯(cuò)了字母的函數(shù)調(diào)用前用了
@ 來(lái)抑制錯(cuò)誤信息,那么程序?qū)](méi)有任何提示的死在那里。
【示例】使用 @ 錯(cuò)誤控制運(yùn)算符屏蔽代碼中的錯(cuò)誤。
運(yùn)行結(jié)果如下:
數(shù)據(jù)庫(kù)連接失??!
2、使用 error_reporting() 函數(shù)屏蔽錯(cuò)誤
PHP 有諸多錯(cuò)誤級(jí)別,使用 error_reporting() 函數(shù)可以設(shè)置 PHP 會(huì)報(bào)告何種錯(cuò)誤,函數(shù)的語(yǔ)法格式如下:
error_reporting([int $level])
其中參數(shù) $level 為設(shè)置錯(cuò)誤級(jí)別,具體可以使用的值可以在《PHP錯(cuò)誤級(jí)別》一節(jié)中查看。如果將 $level 設(shè)置為 0,將關(guān)閉所有 PHP 錯(cuò)誤報(bào)告;如果設(shè)置為 -1,將返回所有的錯(cuò)誤報(bào)告。
【示例】使用 error_reporting() 函數(shù)屏蔽代碼中的錯(cuò)誤。
3、通過(guò) display_errors 參數(shù)屏蔽錯(cuò)誤
這種方法應(yīng)該是最徹底的一種解決辦法,因?yàn)榍皟煞N方法只能作用于單行或者單個(gè)文件,而這個(gè)則是作用于所有的 PHP 文件。
具體的操作方法就是,打開(kāi) php.ini 配置文件,在其中搜索 display_errors,然后將 display_errors 的值設(shè)置為 Off 即可關(guān)閉所有的 PHP 錯(cuò)誤報(bào)告。如下所示:
; 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
標(biāo)題名稱:PHP屏蔽錯(cuò)誤
地址分享:http://www.fisionsoft.com.cn/article/djpjgsj.html


咨詢
建站咨詢
