How to avoid undefined property errors with Null Coalescing operator

If an object has an optional property, we can use ?? to avoid undefined property errors.

Code example of using null coalescing to avoid the undefined property errror.
We use ?? to avoid undefined property errors.

Here, we set a default value since the property $email is null by default.

Had we not used the Null Coalescing operator, we would get an Uncaught Error.

Previous code example without null coalescing leads to an uncaught error.
Without using the Null Coalescing operator, we get an Uncaught Error


Accessing Nested Object Properties

If we’re certain that all objects exist, you can access nested properties using the object operator (->).

Code example of accessing nested properties using the object operator.
Example of accessing nested properties using the object operator.

A null property would trigger a Warning.

Code example of null property triggering a Warning.
In the previous example, a null property would trigger a Warning.

In order to access nested PHP objects without triggering errors we can use the Null Coalescing operator.

Code example of accessing nested PHP objects with the use the Null Coalescing operator
Example of accessing nested PHP objects with the use the Null Coalescing operator.


Using Null Coalescing with Method Calls

Another use case for the Null Coalescing operator is with method calls.

Code example of Null Coalescing operator used with a method.
Example of Null Coalescing operator used with a method.

If a method might return null, we can use ?? to set a default.

Code example of anticipating errors with methods returning nullish values with Null Coalescing.
We anticipate errors with methods returning nullish values with Null Coalescing.


Although my blog doesn’t support comments, feel free to reply via email or X.