What you are looking for is ErrorException
.
You can register error handler like this:
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");
And catch errors:
try
{
echo $a; //Use of undefined variable
}
catch (ErrorException $e)
{
echo $e->getMessage();
}
But you can't handle syntax errors as exceptions neither in php nor in any other language. The reason why you get fatal error when php script actually runs is that php is interpreted. If you tried to compile your php script with any of php compilers, you'd get syntax error at compile-time.
If you want add some logging or something similar when fatal error occurs that you can register shutdown function (using register_shutdown_function
):
register_shutdown_function( "MyShutDownHandler" );
function MyShutDownHandler() {
//Do something here.
}