Home / Get and modify the error reporting level in PHP

Get and modify the error reporting level in PHP

PHP's error_reporting() function allows a script to check what the current error reporting level is and/or modify it. I wouldn't normally recommend changing the error reporting level programatically, but there may be times when it's needed. The nice thing is it's easily possible to get the current level, change it, and then set it back to what it was previously.

Getting the current reporting level

To get the curent reporting level simply call the error_reporting() function without passing any parameters, like so:

$current_error_reporting = error_reporting();

This will return an integer value. You can see for example if E_NOTICE is set in the error reporting level like so:

if($current_error_reporting & E_NOTICE) {
    // do something
}

Changing the error reporting level

To change the error reporting level to something different, pass the new level as the parameter. The value return from the function call is the old error reporting level. The following example changes the error reporting level to everything but notices and stores the old level in a variable.

$old_error_reporting = error_reporting(E_ALL ^ E_NOTICE);

The old error reporting level could then be restored at a later time:

error_reporting($old_error_reporting);

Removing notices from the current reporting level

This final example removes E_NOTICE from the current reporting level, runs some other code, and then restores the old level back again.

// remove E_NOTICE from error reporting and store previous value
$old_error_reporting = error_reporting(error_reporting() ^ E_NOTICE);

// run some other code
// ... code ...

// restore old error reporting level
error_reporting($old_error_reporting);

The above can be tested using the following code. It sets the error reporting level to E_ALL at the start so we can be sure when testing what the initial value is:

error_reporting(E_ALL);
echo error_reporting(), "n";

$old_error_reporting = error_reporting(error_reporting() ^ E_NOTICE);
echo error_reporting(), "n";

error_reporting($old_error_reporting);
echo error_reporting(), "n";

This outputs

6143
6135
6143

which is to be expected: 6143 is E_ALL and 6135 is E_ALL without E_NOTICE.