Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: catching a fatal error (call to member function on a non-object)

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).

like image 325
dukevin Avatar asked Jul 15 '12 03:07

dukevin


1 Answers

In PHP 7

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";
}

In PHP 5

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.

like image 126
Rich Avatar answered Oct 21 '22 08:10

Rich