PHP Custom Error Handler

Goal

I want to eliminate a specific E_WARNING by providing the error number, the error string, the code file and/or the line.

Check PHP version

php -v
PHP 7.2.24 (cli) (built: Oct 25 2019 11:14:44) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.24, Copyright (c) 1999-2018, by Zend Technologies

Code

Let's try this in a PHP console

php -v
php -a

Copy and paste this code:

error_reporting(E_ALL);
class A {
    function __call($name, $arguments) {
        $params = array_shift($arguments);
        if (count($params) == 0) {
            $params = "No params";
        }
        $options = array_shift($arguments);
        if (count($options) == 0) {
            $options = "No options";
        }
        return compact('name', 'params', 'options') + 'no';
    }
}
$a = new A;
print_r($a->b());

Using PHP version 7.2, the result will trigger an E_WARNING on count():

PHP Warning:  count(): Parameter must be an array or an object that implements Countable in php shell code on line 4
  • I want to eliminate this specific E_WARNING.
  • I don't want to remove all warnings of type E_WARNING by using error_reporting(E_ALL & ~E_WARNING);.

Custom error handler

I add this code in the global space:

/**
 * Bypass a PHP error.
 *
 * @link https://www.php.net/manual/en/function.set-error-handler
 */
function error_handler($errno, $errstr, $errfile, $errline) {
    $args = compact('errno', 'errstr', 'errfile', 'errline');
    $error = array(
        'errno'   => E_WARNING,
        'errstr'  => "count(): Parameter must be an array or an object that implements Countable",
        'errfile' => 'php shell code', // OR '/path/filename.php' if the code is in a file
        'errline' => 4,
    );
    return $args + $error == $error;
}
set_error_handler('error_handler');
print_r($a->func());

Result: No more E_WARNING for the specific warning on line 4; the line 8 warning still shows, and other types of errors still show.

If you comment out the errline in both locations in error_handler(), you will hide both line 4 and line 8 warnings.

function error_handler_2($errno, $errstr, $errfile, $errline) {
    // $args = compact('errno', 'errstr', 'errfile', 'errline');
    $args = compact('errno', 'errstr', 'errfile');
    $error = array(
        'errno'   => E_WARNING,
        'errstr'  => "count(): Parameter must be an array or an object that implements Countable",
        'errfile' => 'php shell code', // OR '/path/filename.php' if the code is in a file
        // 'errline' => 4,
    );
    return $args + $error == $error;
}
set_error_handler('error_handler_2');