1

I have a PHP 7 script, that basically does this:

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:

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?

SteeveDroz
  • 6,006
  • 6
  • 33
  • 65
  • What is the code inside `getClassFromSomewhere()`? – ADyson Jun 07 '21 at 14:56
  • Having just tried it online with PHP 8, the message is `Class "Main" not found` - note the quotes. You are testing for `"Class 'Main' not found"` – Nigel Ren Jun 07 '21 at 14:58
  • Might be worth a read https://stackoverflow.com/questions/4421320/why-doesnt-php-catch-a-class-not-found-error/4421332 – RiggsFolly Jun 07 '21 at 15:01
  • @NigelRen, that's right! It's single quotes in PHP 7 and double in PHP 8. Please convert your comment into an answer so I can accept it! – SteeveDroz Jun 07 '21 at 16:07

1 Answers1

3

The only difference seems to be that PHP 8 uses double quotes round the class name -

Class "Main" not found

whereas it previously (as in your current code) used single quotes...

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.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55