Method Call on Non-Object

PHP strictly distinguishes between objects and scalar values. While an object can contain methods, in PHP a scalar type like a string or a boolean is not represented as an object and thus does not provide any methods that can be called.

Consequently, executing the following code leads to an error:

$x = 'not-an-object';
$x->method();

Even before attempting to call the requested method, PHP refuses to continue because of the unsupported type:

PHP Fatal error:  Call to a member function method() on string in ...

This is a very common mistake, seen mostly when an explicit type declaration is missing on a method’s signature or when the returned value’s type was not verified. This error also got replaced by an engine exception in PHP 7 and thus can now be handled with a simple catch:

$x = 'not-an-object';
try {
    $x->method();
} catch (Error $error) {
    var_dump($error);
}

Executing the code shown will render the following output

object(Error)#1 (7) {
  ["message":protected]=>
  string(44) "Call to a member function method() on string"
  ...