Skip to content
Advertisement

How to catch a fatal error both in PHP 7 and 8?

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

JavaScript

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

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

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

JavaScript

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement