Fatal error: Call to a member function on a non-object.

This fatal error will occur if you attempt to call a function on a variable that is not an object.

For example.

//Attempt to call the function getList.

If the variable $test above is not an object, then our code with spit out the following error.

Fatal error: Call to a member function getList() on a non-object on line […]

This can happen because of four reasons.

  1. You did not create the object in the first place.
  2. The variable does exist, but it is not an object. In other words, it is an integer, an array or a string.
  3. You did create the object. However, your code is overwriting it or unsetting it at a later stage.
  4. The object in question does not exist inside the current scope. For example, you are attempting to reference the object inside of another function without passing it through as a parameter.

Take the following example of a scope issue.

//Create our object.
$car = new Car();

//Example function.
function test(){
    //Attempt to call the object's drive method.

//Call the function.

The code above will result in a fatal error. Why? Because the object $car does not exist inside of the scope of the test function.

Consequently, our PHP script will throw a fatal error about how we are attempting to call a member function on a non-object.

To fix this particular error, we will need to pass the $car object in as a function parameter.

//Doing it the right way.
function test($car){ 
    //Attempt to call the object's drive method. 

//Call the function.

Using the is_object function.

In some cases, the creation of an object might be outside of your control.

In situations like this, you will need to check if the object exists or not before you attempt to use it. You can do this by using PHP’s native is_object function.

An example of this function in action.

//If $myObject is actually an object.
    //Call the function.

Although the above piece of code will “fix” the fatal error, it does not take into account the fact that the variable might not exist.

In other words, we are still leaving ourselves open to nasty “Undefined Variable” notices.

To fix this, we can use the isset function in conjuction with the is_object function.

//We're expecting an object by the name $myObject
if(isset($myObject) && is_object($myObject)){
    //$myObject exists AND it is an object.
} else{
    //Object was not found

The function isset checks to see if the variable exists or not. If it does exist, then the IF statement will check to see if it is an object.

Hopefully, this article helped!