58

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?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Majid Fouladpour
  • 27,709
  • 19
  • 72
  • 126
  • possible duplicate of [Reference - What does this symbol mean in PHP?](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – Quentin Dec 19 '11 at 16:22
  • 2
    @ is also know as an atpersand. – jofitz Feb 17 '15 at 09:46

5 Answers5

75

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);
Harmen
  • 21,490
  • 3
  • 53
  • 74
Sarfraz
  • 367,681
  • 72
  • 526
  • 573
11

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

Tyson of the Northwest
  • 2,016
  • 2
  • 20
  • 33
7

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.

SenorPuerco
  • 839
  • 2
  • 8
  • 19
3

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

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Hydrino
  • 537
  • 3
  • 9
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:

$ php -r 'var_dump($_POST["hn"]);'
PHP Warning:  Undefined array key "hn" in Command line code on line 1
NULL

The output with silencing warnings (@):

$ php -r 'var_dump(@$_POST["hn"]);'
NULL

Obtaining the same result with the modern null coalescing operator (??):

$ php -r 'var_dump($_POST["hn"] ?? null);'
NULL