If an object has an optional property, we can use ?? to avoid undefined property errors.
We use ?? to avoid undefined property errors. (click on the image to open in a new tab)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.
Without using the Null Coalescing operator, we get an Uncaught Error (click on the image to open in a new tab)
Accessing Nested Object Properties
If we’re certain that all objects exist, you can access nested properties using the object operator (->).
Example of accessing nested properties using the object operator. (click on the image to open in a new tab)A null property would trigger a Warning.
In the previous example, a null property would trigger a Warning. (click on the image to open in a new tab)In order to access nested PHP objects without triggering errors we can use the Null Coalescing operator.
Example of accessing nested PHP objects with the use the Null Coalescing operator (click on the image to open in a new tab)
Using Null Coalescing with Method Calls
Another usecase for the Null Coalescing operator is with method calls.
Example of Null Coalescing operator used with a method. (click on the image to open in a new tab)If a method might return null, we can use ?? to set a default.
We anticipate errors with methods returning nullish values with Null Coalescing. (click on the image to open in a new tab)
Although my blog doesn’t support comments, feel free to reply via email or X.