'At' symbol before variable name in PHP: @

2019-01-14 00:00发布

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?

5条回答
孤傲高冷的网名
2楼-- · 2019-01-14 00:21

It suppresses warnings if $_POST['something'] is not defined.

查看更多
狗以群分
3楼-- · 2019-01-14 00:21

Something that others forgot to mention is that besides ignoring the NOTICE, the variable will be set to NULL.

查看更多
家丑人穷心不美
4楼-- · 2019-01-14 00:36

It won't throw a warning if $_POST['hn'] is not set.

查看更多
Lonely孤独者°
5楼-- · 2019-01-14 00:41

The @ is the error suppression operator in PHP.

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

See:

Update:

In your example, it is used before the variable name to avoid the E_NOTICE error there. If in the $_POST array, the hn key is not set; it will throw an E_NOTICE message, but @ is used there to avoid that E_NOTICE.

Note that you can also put this line on top of your script to avoid an E_NOTICE error:

error_reporting(E_ALL ^ E_NOTICE);
查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-01-14 00:42

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.

查看更多
登录 后发表回答