Sometimes, my script cannot read output by a server and the following error occurs:
PHP Fatal error: Call to a member function somefun() on a non-object
This is not something that can't be fixed on my end but this causes my script to crash. Is there a way I can create a function that gets run when this particular error occurs? I don't think it's practical to make a try-catch or similar because I would have to find every instance where a member function gets called and test whether the object exists or not (several thousand).
Yes, catch an "Error" throwable, see http://php.net/manual/en/language.errors.php7.php
Demo: https://3v4l.org/Be26l
<?php
$x = "not an object";
try {
$x->foo();
} catch (\Throwable $t) {
echo "caught";
}
Is there a way I can create a function that gets run when this particular error occurs?
Yes, you can use "register_shutdown_function" to get PHP to call a function just before it dies after encountering this error.
PHP: catching a fatal error (call to member function on a non-object)
It is not possible to recover from this error, if that is what you mean by "catch", as PHP has defined "Call to a member function on a non-object" as a "fatal" error. See PHP turn "Call to a member function on a non-object" into exception for some discussion on why this might be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With