Home / Snippets / How to Access stdClass Property that has Spaces in PHP
How to Access stdClass Property that has Spaces in PHP cover

How to Access stdClass Property that has Spaces in PHP

4.1K

3 years ago

0 comments

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!
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this