PHP alias @ function

2019-06-21 23:07发布

问题:

I'm new to PHP and I'm confused seeing some examples calling a function with a @ prefix like @mysql_ping().

What is it for? Googling / searching is not much of a help since @ gets discarded and 'alias' is not good enough keyword.

回答1:

@ suppresses errors, warnings and notices.

You can use it for good purpose if you complement it with a custom error handler or with due check of $php_errormsg variable so you can handle errors properly.

In my experience, this proper usage is not seen very much and is instead used a lot in the bad way, just to hide errors without acting on them.

More info at http://www.php.net/manual/en/language.operators.errorcontrol.php



回答2:

It suppresses the output of error messages. Contrary to another commentator here, I think that it is good programming practice to use it (especially if you are developing a web app, where the output would be mixed in the html of the output page).

Functions like mysql_connect return a resource identifier, or FALSE on errors. Use @mysql_connect(...) and check the return value.



回答3:

Googling for "php at symbol" suggests that it asks PHP to not display any error messages that the call causes.



回答4:

It suppresses any errors that might otherwise be output.

It is a recipe for pain and hardship, as it inevitably leads to difficulties when an error does occur, you are bound to spend hours tracking down the cause. If the @ operator hadn't been used, then the error would have been found in seconds.

There is no good reason to use it, use the display_errors and error_log ini settings to prevent errors from displaying on a live site, and let them be shown on your dev site.

If there is an error that you don't want to see, you're better off just fixing it than suppressing it!

If it's something in an external lib and outside your control, just write it to the logs, turn off display_errors on production, and live with it. Because there's no telling whether the error you're suppressing now and are happy to live with will ALWAYS be the error that is thrown from there.

@ === BAD



回答5:

Suppress error messages: http://bytes.com/forum/thread10951.html



回答6:

Prefixing a function with the a symbol stops it triggering the PHP error handler if an error occurs. Bear in mind that you must do all the error handling yourself if you decide to use it.

$test = @file_get_contents('nonexistant.file');
if(!$test)
{
    die('Failed');
}

A better practice is to turn display_errors off and use custom error handlers (see Error Exception).



回答7:

Sometimes it is useful- especially if the admin doesn't want you to play with the php environment or the value isn't important and is mainly cosmetic. Do remember, though; it's a workaround, not a panacea.

[...]

.$foutDate = @filemtime($keyring); /* Don't care, as we've already established file */

$f["date"] = $foutDate;

$f["fullDate"] = date("r", $foutDate);

[...]