Ok, this took some time to break it down. Here it is:
There is an included faulty script which is the following for the remainder of this post:
faulty.php
<?php
$a = 4 // missing semicolon
$b = 2;
Then consider the following script for handling the error. Note, that the custom exception handler is initially not registered.
script.php
<?php
// disable default display of errors
ini_set('display_errors', 0);
// register functions
#set_exception_handler('catchException'); // initially not set
register_shutdown_function('catchError');
// define error function
function catchError(){
echo "PHP version: ".phpversion();
if(is_null(error_get_last())) echo "<h1>No errors fetched!</h1>";
else echo "<h1>Error fetched:</h1>";
var_dump(error_get_last());
}
// define exception function (not used in all examples)
function catchException(){}
// include faulty script
include("D:/temp/faulty.php");
Result with no custom exception handler
The results for PHP 5 and 7 are identical. The error_get_last() function returns the last ocurred error (Screenshot).
Result with custom error handler
Now we set a custom function uncommenting the line
set_exception_handler('catchException');
This will work fine in PHP 5, however in PHP 7 the error_get_last()
function returns NULL
(Screenshot).
Question
Why is this? Especially confusing as the custom exception handler is empty, e.g. not "successfully handling" the error.
How to prevent this?
All the best and thanks for hints!
Update: problem and solution
The thing (not really a problem) is that PHP 7 throws an exception of type ParseError rather then producing an error. Thus, it is best handled with an exception handler. Make a nice exception handler to handle the exception well:
function catchException($e){
echo "<h1>".get_class($e)."</h1>";
echo $e->getMessage()."<br>";
}