PHP: Error Suppression CodeUnit 15 DEC 2009

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:

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.