Change error reporting during the execution of a class

It’s generally not a good idea to mess about with error reporting levels – just turn them on while developing and off in production.

However, I recently came across a situation where I wanted to suppress the error notices being generated while developing a particular class.

An autoloader class was generating notices while looking for files – a useful feature as it shows the paths where it wasn’t finding the files, so I didn’t want to change the source of the error notices.

Instead, the solution was to change the error reporting levels in the class using the autoloader using PHP’s error_reporting function. This function returns the previous error reporting level when called, allowing it to be set back later on.

The code:

function __construct( \PDO $db, $p = array() )
	// Change error reporting level
	$this->old_error_reporting_level = error_reporting( E_ERROR | E_WARNING | E_PARSE );


function __destruct()
	// Change error reporting level back
	error_reporting( $this->old_error_reporting_level );

Maybe someone else will find this useful!