Fix PHP Notice: Undefined property

This is a guide on how to fix the following PHP notice:

Notice: Undefined property: stdClass::$propertyThatDoesNotExist in /path/to/file.php on line LINE NUMBER

Essentially, this notice will occur if your PHP code attempts to reference an object property that does not exist.

Typos and misspellings.

Firstly, you will need to make sure that you haven’t misspelled the name of the property that you are attempting to reference.

Take the following PHP class as an example:

As you can see, the class above has one property called User::$loggedIn.

Now, let’s do something like this:

In the code snippet above, I mistakenly referenced a property called User::$isLoggedIn. The correct name of the property is actually called User::$loggedIn. As a result, the following notice will occur:

Notice: Undefined property: User::$isLoggedIn in /path/to/file.php

The “Undefined property” notice above was caused by a simple misspelling.

While we are on the subject of typos, it is worth pointing out that class properties in PHP are case sensitive. As a result, mistakenly using a capital letter instead of a lowercase letter will also cause this error.

Referencing an object property doesn’t exist yet.

In certain cases, the property that you are attempting to reference might not exist yet. Take the following PHP class as an example:

The class above has one function called setName, which dynamically creates an object property called Person::$name. i.e. The $name property will not exist until the setName function has been called. As a result, the following piece of code will result in an “Undefined property” notice:

To fix this, we will obviously need to use the setName function before we attempt to access Person::$name:

Check to see if it exists before using it.

If you are unsure about whether an object property exists or not, you can always use the isset function like so:

In the PHP code above, we “fixed” the notice by adding an isset check. This works because non-existent class properties equate to null.

This kind of check may be necessary when you are dealing with JSON strings that have been decoded into a PHP object. In the past, I have come across a number of APIs that will add and omit certain JSON fields from their response depending on the circumstances.

Example: If a certain piece of data is missing from a certain record, they may remove the field from the response instead of sending it back with a null or a FALSE value. In cases like this, you will need to make use of the isset function.

Hopefully, this guide helped to clear up some confusion!

Facebook Comments