set_error_handler() doesn't work for FATAL error

Nope, that's just a limitation of set_error_handler(); it doesn't handle all errors.

The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

The register_shutdown_function() and error_get_last() is a decent workaround.


There are only hackish ways to solve it, e.g. by using register_shutdown_function() and then checking if an error occurred inside that function.

PHP has log_errors for a reason, you can make PHP log any error to syslog or a logfile without a single line of custom code. So using set_error_handler() for this purpose is not needed at all and should be avoided unless you need e.g. a stacktrace.


As others have pointed out we can use register_shutdown_function() and error_get_last() in following fashion.

The below implementation will catch the errors which are not even caught by \Throwable as tested in php 7.1. It should work for previous PHP versions too. It should only be implemented in your development environment(by just adding it in your development config file) and shouldn't be done in production environment.

Implementation

register_shutdown_function(function () {
    $err = error_get_last();
    if (! is_null($err)) {
        print 'Error#'.$err['message'].'<br>';
        print 'Line#'.$err['line'].'<br>';
        print 'File#'.$err['file'].'<br>';
    }
});

Example Error

Error# Class Path/To/MyService contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Path/To/MyServiceInterface::add)
Line# 12
File# Path/To/MyService.php