How can a PHP script define a variable that is true when a fatal error occurs, in order to end the script with a custom message?

To handle fatal errors in PHP and end the script with a custom message, you can define a variable that will be set to true when a fatal error occurs. This can be achieved by using the register_shutdown_function() function in PHP to register a function that checks for any fatal errors and sets the variable accordingly. Then, you can check this variable after the script execution to determine if a fatal error occurred and display a custom message.

<?php
// Define a variable to track fatal errors
$fatalError = false;

// Register a shutdown function to check for fatal errors
register_shutdown_function(function() use (&$fatalError) {
    $error = error_get_last();
    if ($error !== null && $error['type'] === E_ERROR) {
        $fatalError = true;
    }
});

// Your PHP script code goes here

// Check if a fatal error occurred and display a custom message
if ($fatalError) {
    echo "A fatal error occurred. Script execution halted.";
    exit;
}
?>