PHP turn "Call to a member function on a non-object" into exception

error-handling, php

Solution

This has been fixed in PHP 7:

- http://php.net/manual/en/language.errors.php7.php

- https://wiki.php.net/rfc/engine_exceptions

In PHP 7+, this code will now throw, instead of causing an irrecoverable fatal error.

Problem

When I am running "Behat" steps, the Behat error handler turns "Trying to get property of non-object" errors into exceptions. This is very helpful, as it causes the step to be marked as failed, and allows the test run to continue at the next scenario. However, "Call to a member function on a non-object" errors are fatal, and immediately halt the test execution (including aborting writing the results to xml). This is unhelpful. My questions are: What is the difference between these two errors? Are they different "error levels"? Where is that documented? I have searched the PHP site and Google, and cannot find the canonical reference, just lots of questions about debugging specific instances of each error. Is there any way to convert the latter error into an exception, instead of halting the script entirely? It doesn't seem to me that dereferencing "`null`" with "`->`" would be an error that "can not be recovered from, such as a memory allocation problem". Update: It looks like this is just a known issue with PHP. See: - #51882 Call To Member Function on Non-Object Should Throw An Exception - #46601 E_RECOVERABLE_ERROR for "Call to a member function on a non-object" - #51848 Non-object method call errors should be catchable with set_error_handler() - #63538 "Call to undefined function" should be catchable Some people say it's "by design", but I think it's just an artefact of the error levels being defined before objects were added to PHP. In a non-OO language calling a non-existent function is a serious error, and I can see how it might be described as "fatal" or "not recoverable" (although, in a non-OO language where functions can be defined on-the-fly, even that seems overly pessimistic). These days, now that you can do "`$a->f()`" on any old `$a`, it is far more likely that "`f`" may not exist, and it seems like it should not be a fatal error (cf. Java where this would be a NullPointerException). I suppose that leads me to a new question: _ 3. How could you patch PHP to make "Call to a member function on a non-object" errors non-fatal, without massively breaking backwards compatibility, and what steps could you take to maximise the likelihood of that patch being accepted into PHP? Update 2 re patching PHP: There is some limited support on the PHP internals mailing list for making this fix. Now I just need to write a patch to fix this and create an RFC.

Original source