简体   繁体   中英

'@' symbol in php, e.g. '@$name[1]'?

All,

What is the signification of the '@' symbol in PHP? For example, what does it mean in this statement:

$sd = (@$argv[1]) ? getdate(strtotime($argv[1])) : getdate();

I understand the ternary operator '?', but I have no idea what the '@' means...

The code is sample code from the (very good!) cs75.net Harvard extension course.

Thanks,

JDelage

The @ symbol suppresses any errors which may be produced in the course of the function (or expression).

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.

Error suppression should be avoided if possible as it doesn't just suppress the error that you are trying to stop, but will also suppress errors that you didn't predict would ever occur. This will make debugging a nightmare.

The @ supressess any error messages from the expression, that is, if E_NOTICE is set

$argv = Array("Only one object.");
if ($argv[1]) { print "Argv[1] set"; }

would cause an warning, but

$argv = Array("Only one object.");
if (@$argv[1]) { print "Argv[1] set"; }

would simply not print anything.

Keep in mind though, that it's a much better practice to use

if (!empty($var)) { print "Argv[1] is set and non-false."; }

instead.

It's the solution for the programmer who can't be arsed checking if $argv[1] is defined and doesn't want to see a warning telling him how lazy he is. Also known as error suppression .

Others have explained that @ suppresses error messages. Fun fact from Ilia Alshanetsky's talk on "PHP and Performance":

The error blocking operator is the most expensive character in PHP's alphabet. This seemingly innocuous operator actually performs fairly intensive operations in the background:

$old = ini_set("error_reporting", 0);
action();
ini_set("error_reporting", $old);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM