PHP: Calling Methods on Non-Objects
PHP has subtly changed the wording of this error between various versions of the language, which can trip up your log aggregators when you upgrade so I thought I'd give a quick rundown of the changes around the "call to member function on non-object" error in PHP, up to and including PHP 7 which has an entirely new error handling approach.
As an example I'm using this piece of nonsense which just sets $ato be a number and then attempts to call a method on it:<?php$a = 1;$a->grow();
This doesn't work but the exact output varies between versions of PHP.
In PHP 5.5(and maybe earlier, I don't seem to have any of the dead versions compiled on this machine for some reason), the error message reads like this:
Fatal error: Call to a member function grow() on a non-object in /home/lorna/.../method_non_object.php on line 7
So far, so familiar.
In PHP 5.6the error message got a bit more specific and tells us what kind of a non-object we're dealing with:
PHP Fatal error: Call to a member function grow() on integer in /home/lorna/.../method_non_object.php on line 7
However in PHP 7, everything changes. Look at the error message output by the exact same sample code:
Fatal error: Uncaught Error: Call to a member function grow() on integer in /home/lorna/.../method_non_object.php:7
This message looks completely different because PHP 7 has a whole new way of handling errors. Not every part of PHP has switched over to the new way but it's both excellent and quite a big change. The clue in the message which starts with the word "Uncaught". Usually we'd expect the next word to be "Exception" but in PHP 7 there is a new Errorobject, which can be intercepted using the catchconstruct that we're already familiar with.
I'll write more about the errors in PHP 7 in a separate post but in the meantime you can read more about them in the manual (this might be my favourite manual page URL): http://php.net/error