Using @ to disable errors

If you find an error message particularly annoying and you are sure it definitely does not apply to you, PHP has a method for you to silence the message entirely. If you place an at symbol, @, before a function that generates an error, PHP will catch the error and silence it entirely. Consider the following two complete scripts:

<?php
    foo();
?>
<?php
    @foo();
?>

In script one, the undefined function foo() is called. When this script is run, PHP will halt execution at the undefined function, and print out a fatal error message. However, when the second script is run, PHP will attempt to call the foo() function, fail, but will not halt execution or print out an error - all thanks to the @ symbol before the function call.

While there are legitimate uses for suppressing errors in this way, it is not advised, because it usually works in the same way that sweeping dust under a carpet does not make a house any cleaner - hiding a problem is not the same as solving it! If you explicitly wish to have errors suppressed with @, it is strongly advised that you always write your own code to check return values of functions.

Author's Note: Only use @ if you're absolutely certain the error doesn't apply to you!

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: phpinfo() >>

Previous chapter: Custom exception handlers

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.