PHP: Error Suppression

PHP-logoLet’s start this off with a quick, NEVER should you be suppressing errors instead of trying to resolve the scenarios in which an error can occur.

However, if you feel that you absolutely HAVE to suppress minor error notifications that impacts on the script’s overall functioning, PHP does provide a single error control operator: the at sign (@).

Prepending the @ sign to an expression in PHP forces any error messages that might be generated by that expression to be ignored. Note that the operator only works on expressions. Essentially if you can take the value of something, you can prepend the @ operator to it.

For example, you can use it in front of variables, function and include calls, constants, etc., but you cannot use it in front of function or class definitions, or in front of conditional structures such as if and foreach for example.

Obviously using @ can be quite dangerous as it can lead to situations where your script is inexplicably dying with no notification that it has in fact failed, so again this is something you should be using with extreme caution, if using at all!

Example usages:

/* Intentional file error */
$my_file = @file ('non_existent_file') or
die (
"Failed opening file: error was '$php_errormsg'");

// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.
?>

Related Link: http://php.mirror.ac.za/manual/en/language.operators.errorcontrol.php

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged , , . Bookmark the permalink.
    blog comments powered by Disqus