I have a script that uses DOMDocument
. In some environments, it fails, presumably due to some module is not loaded. What I’m trying to do is to provide a user of this script instructions to fix this behavior.
Here’s a minimal script to reproduce the problem:
<?php
echo 'start!';
try {
$doc = new DOMDocument();
} catch (Exception $e) {
echo 'catched';
}
echo 'end';
?>
If I open it in browser (served by my current server, involving Nginx), I see just start!
(and the return code is 500
; same output if I omit try..catch
). So the problem is not only in detecting whether the right module is installed (should I use extension_loaded('dom')
to check it?), but also the fact that try..catch
doesn’t seem to work (I don’t get catched
in the output; I’m using PHP 7.4.3 in the current case).
Any suggestions of how should I process this case correctly?
3
Answers
You can test for the class with
class_exists()
Eg
When a class is not found, an
Error
is raised. That class does not extendException
, which is why your code doesn’t catch it.This will work:
Or:
Of course, you can directly test
extension_loaded('dom')
to detect if the extension is available.as of PHP7, when a class cannot be found, it throws an
Error
, which is not a descendant ofException
(because the PHP designers got it wrong), so your(Exception $e)
doesn’t qualify. To catch anything thrown, usecatch (Throwable $e)
(fwiw both Error and Exception are descendant of Throwable)