I have a PHP 7 script, that basically does this:
JavaScript
x
try {
$class = getClassFromSomewhere();
}
catch(Error $e) {
if ("Class 'Main' not found" == $e->getMessage()) {
echo 'Run "php generate-main-class" to generate the class.'.PHP_EOL;
exit;
} else {
throw $e;
}
}
To be clear: if the class I am looking for is “Main” and can’t be found, I must display the text, else it’s supposed to throw the exception anyway.
It works well with PHP 7, but PHP 8 does not catch the error. Instead, it shows:
JavaScript
Fatal error: Uncaught Error: Class "Main" not found in
How am I supposed to catch a “Class not found” fatal error in PHP 8 in a backwards compatible way?
Advertisement
Answer
The only difference seems to be that PHP 8 uses double quotes round the class name –
JavaScript
Class "Main" not found
whereas it previously (as in your current code) used single quotes…
JavaScript
Class 'Main' not found
You could alternatively just check if the class exists prior to trying the code (In PHP how can i check if class exists?), which may be cleaner than causing an error.