PHP simplexml_load_file()需要一个@前缀


PHP simplexml_load_file() does this need a @ prefix

我正在使用以前的开发人员代码,他的许多代码都隐藏了@ 的错误

一个例子是:

if(!file_exists($filename)) 
    throw new Exception("file '$filename' does not exist.");
$xmlObject = @simplexml_load_file($filename);       
if($xmlObject === false) 
    throw new Exception("Could not load '$filename' check syntax and file has read permission.");

我知道使用@会隐藏错误,但这种做法是好还是坏?

只要有其他错误捕获,比如上面的例子,使用@是可以接受的,因为它隐藏了PHP的标准错误输出。

然而,使用@来隐藏错误而不采取任何措施来纠正错误被认为是一种糟糕的做法。

这很糟糕。你应该经常检查以确保一切都是合法的。开发良好的干净代码将使您能够在出现问题时识别问题。通过使用@,它将完全抑制那些可能由其他原因引起的错误。你永远不会知道,故障排除变得更加困难。

以你上面的例子为例。

$xmlObject = @simplexml_load_file($filename);

此人已经在检查该文件是否存在。你可能会删除@符号,然后用try-catch块来更改它。

Try {
  $xmlObject = simplexml_load_file($filename);
catch....

非常糟糕。

首先开发代码。然后你开始测试它,如果有什么问题,你想通过看到错误来知道哪里出了问题。所以你不想把它们藏起来。

如果你已经有了开发和调试状态,并想把它放在网上,你必须关闭错误

<?php
ini_set('display_errors', 'Off');
error_reporting( null );
?>

用户现在看不到任何错误。更好的方法是将其添加到.htaccess文件中:

# Turn off the errors
php_flag display_startup_errors off
php_flag display_errors off

因此,错误已经被隐藏,因此不需要@

我不记得有哪个状态需要隐藏错误。