8.15. Tuning Error Handling
Problem
You want to alter the error-logging sensitivity on a particular page. This lets you control what types of errors are reported.
Solution
To adjust the types of errors PHP complains about, use
error_reporting( )
:
error_reporting(E_ALL); // everything error_reporting(E_ERROR | E_PARSE); // only major problems error_reporting(E_ALL & ~E_NOTICE); // everything but notices
Discussion
Every error generated has an error type
associated with it. For example, if you try to array_pop( )
a string, PHP complains that “This
argument needs to be an array,” since you can only
pop arrays. The error type associated with this message is
E_NOTICE
, a nonfatal runtime problem.
By default, the error reporting level is E_ALL & ~E_NOTICE
, which means all error types except notices. The
&
is a logical AND
,
and the ~
is a logical NOT
.
However, the
php.ini-recommended
configuration file sets the
error reporting level to E_ALL
, which is all error
types.
Error messages flagged as notices are runtime
problems that are less serious than
warnings.
They’re not necessarily wrong, but they indicate a
potential problem. One example of an E_NOTICE
is
“Undefined
variable,” which occurs if you try to use a variable
without previously assigning it a
value:
// Generates an E_NOTICE foreach ($array as $value) { $html .= $value; } // Doesn't generate any error message $html = ''; foreach ($array as $value) { $html .= $value; }
In the first case, the first time though the
foreach
,
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.