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,
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access