我看到过在某些函数前使用@,比如:

$fileHandle = @fopen($fileName, $writeAttributes);

这个符号有什么用?


当前回答

还要注意,尽管错误被隐藏,任何自定义错误处理程序(使用set_error_handler设置)仍将执行!

其他回答

@抑制错误信息。

它被用于如下代码片段:

@file_get_contents('http://www.exaple.com');

如果域名“http://www.exaple.com”不可访问,则会显示错误,但没有显示@。

如果打开失败,则生成E_WARNING级别的错误。你可以使用@来屏蔽这个警告。

就像之前已经有人回答的那样:@操作符抑制了PHP中的所有错误,包括通知、警告甚至严重错误。

但是:请不要使用@操作符。

Why?

好吧,因为当您使用@操作符来抑制错误时,当错误发生时,您完全不知道从哪里开始。在一些开发人员经常使用@操作符的遗留代码中,我已经获得了一些“乐趣”。特别是在文件操作、网络调用等情况下。这些都是许多开发人员推荐使用@操作符的情况,因为在这里发生错误时,@操作符有时超出了范围(例如,3rdparty API可能无法访问,等等)。

但为什么还不用呢?让我们从两个角度来看看:

As a developer: When @ is used, I have absolutely no idea where to start. If there are hundreds or even thousands of function calls with @ the error could be like everyhwere. No reasonable debugging possible in this case. And even if it is just a 3rdparty error - then it's just fine and you're done fast. ;-) Moreover, it's better to add enough details to the error log, so developers are able to decide easily if a log entry is something that must be checked further or if it's just a 3rdparty failure that is out of the developer's scope.

As a user: Users don't care at all what the reason for an error is or not. Software is there for them to work, to finish a specific task, etc. They don't care if it's the developer's fault or a 3rdparty problem. Especially for the users, I strongly recommend to log all errors, even if they're out of scope. Maybe you'll notice that a specific API is offline frequently. What can you do? You can talk to your API partner and if they're not able to keep it stable, you should probably look for another partner.

简而言之:你应该知道有@这样的东西存在(知识总是好的),但不要使用它。许多开发人员(尤其是那些来自他人的调试代码)将非常感激。

假设我们没有使用“@”操作符,那么我们的代码看起来像这样:

$fileHandle = fopen($fileName, $writeAttributes);

如果我们试图打开的文件没有找到该怎么办?它将显示一条错误消息。

为了抑制错误消息,我们使用“@”操作符,例如:

$fileHandle = @fopen($fileName, $writeAttributes);

它抑制错误消息-请参阅PHP手册中的错误控制操作符。