“在” PHP 中变量名前的符号:@$_POST
我见过函数调用前面有一个 at 符号来关闭警告。今天我浏览了一些代码,发现了这一点:
$hn = @$_POST['hn'];
它在这里有什么好处?
I've seen function calls preceded with an at symbol to switch off warnings. Today I was skimming some code and found this:
$hn = @$_POST['hn'];
What good will it do here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
@
是 PHP 中的错误抑制运算符。参见:
更新:
在您的示例中,它在变量名称之前使用,以避免出现
E_NOTICE
错误。如果在$_POST
数组中,hn
键没有设置;它会抛出E_NOTICE
消息,但使用@
来避免E_NOTICE
。请注意,您还可以将此行放在脚本顶部以避免
E_NOTICE
错误:The
@
is the error suppression operator in PHP.See:
Update:
In your example, it is used before the variable name to avoid the
E_NOTICE
error there. If in the$_POST
array, thehn
key is not set; it will throw anE_NOTICE
message, but@
is used there to avoid thatE_NOTICE
.Note that you can also put this line on top of your script to avoid an
E_NOTICE
error:如果未设置 $_POST['hn'] ,它不会发出警告。
It won't throw a warning if $_POST['hn'] is not set.
这意味着,如果未定义 $_POST['hn'],则 PHP 不会抛出错误或警告,而是将 NULL 分配给 $hn。
All that means is that, if $_POST['hn'] is not defined, then instead of throwing an error or warning, PHP will just assign NULL to $hn.
如果未定义 $_POST['something'] ,它会抑制警告。
It suppresses warnings if $_POST['something'] is not defined.
我在 11 年后回答了有关现代 php 的完整性问题。
从 php 7.0 开始, 空合并运算符是消除警告的更直接的替代方案。
??
运算符就是为此目的而设计的(除其他外)。如果没有
@
,则会显示警告:带有静音警告的输出 (
@
):使用现代空合并运算符获得相同的结果 (
??
):I'm answering 11 years later for completeness regarding modern php.
Since php 7.0, the null coalescing operator is a more straightforward alternative to silencing warnings in that case. The
??
operator was designed (among other things) for that purpose.Without
@
, a warning is shown:The output with silencing warnings (
@
):Obtaining the same result with the modern null coalescing operator (
??
):