In this short snippet, you will learn how to accessing stdClass/Class properties with spaces in PHP. This scenario typically arise when you are using a JSON decode method in PHP which will then return a stdClass object. For this example do imagine that you have stdClass like below.
{#1293
+"First Name": "John",
+"Last Name": "Doe",
+"Address": "Street 123"
}
Generally, if there are no spaces then you could just make use of the normal way "$object->property" but if there is space like the "First Name" and "Last Name" like above, then you can make use of the curly brackets.
"{}".
<?php
$property = 'First Name';
$object->{$property};
Or you can simply write it into a one-liner.
$object->{'First Name'};
If you want to check using the null coalescing operator then you can write it like below.
$object?->{'First Name'};
By now you should be able to get the value of the class properties that has a space in PHP. if you find this tutorial helpful do share it with your friends and cheers!
Leave a reply