16

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

5

3 Answers 3

46

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.

0

You might be looking for http://www.php.net/manual/en/function.set-error-handler.php. You would have to write your own error handler and check the errorcode for whether you want to display the error or not.

2
  • What level error is the one I'm having? E_ERROR? If so, this wouldn't work
    – dukevin
    Commented Jul 15, 2012 at 4:05
  • I'm sorry, you are right. Is creating a dummy-function an option? Or is the function name created dynamically?
    – PhilMasteG
    Commented Jul 15, 2012 at 4:08
-1

try use function_exists to check that function is exist:

if (function_exists("somefun")) {
   ...
}

or use method_exists to validate class method.

3
  • I am already aware of this solution but the problem is that this can happen anywhere in the code (maybe a 1000 different places), I don't want to duplicate this that many times
    – dukevin
    Commented Jul 15, 2012 at 4:01
  • If you were able to catch the error, would you be able to respond to it in a generic way that's applicable in all 1000 places? Or would the possible error conditions all need to do something different in response anyway?
    – octern
    Commented Jul 15, 2012 at 4:14
  • I would be able to respond appropriately
    – dukevin
    Commented Jul 15, 2012 at 4:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.