8.15. Tuning Error Handling


You want to alter the error-logging sensitivity on a particular page. This lets you control what types of errors are reported.


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


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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.