How to Read Properties of a stdClass Object in PHP
json_decode turns a JSON object into a PHP object of the class stdClass, a plain object with one property for each JSON key. You read its properties with the arrow operator, $user->name, not with square brackets.
Syntax
$<object>-><property>
$<object>-><property> ?? <fallback>
| Part | What it does |
|---|---|
-> | Reads a property of an object. |
?? <fallback> | Uses <fallback> when the property is missing or null, without a warning. |
The PHP manual for stdClass: "A generic empty class with dynamic properties." It adds that "Several PHP functions also create instances of this class, e.g. json_decode()".
The Example
The example decodes a small JSON object, prints its class and one property, and asks for a property it doesn't have.
Prerequisites
- PHP for the command line. This guide uses PHP 8.6.0.
Step 1: Write the Code
Create a file named main.php:

<?php
$user = json_decode('{"name": "Ada", "role": "admin"}');
echo get_class($user), "\n";
echo $user->name, "\n";
echo $user->email ?? 'no email', "\n";
Step 2: Run It
php main.php
stdClass
Ada
no email

get_class confirmed the object's class, ->name read a property, and ?? covered the missing email. The command is the same in zsh, bash and PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Reading it like an array, as in $user['name'] | Fatal error: Uncaught Error: Cannot use object of type stdClass as array | Use $user->name |
Reading a missing property without ?? | Warning: Undefined property: stdClass::$email and null | Add ?? 'default' |
Expecting an array from json_decode | You get an object unless you ask for an array | Pass true as the second argument |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Cannot use object of type stdClass as array | Square brackets on an object | Switch to -> |
Undefined property: stdClass::$… | The JSON had no such key | Check the key, or use ?? |
FAQ
How do I get an array instead?
json_decode($json, true) returns an associative array: in my check, gettype said array and $user['name'] gave Ada.
Can I add properties to a stdClass?
Yes: $user->email = 'ada@example.com'; adds one. That's what "dynamic properties" means.
Conclusion
A stdClass object, such as one from json_decode, exposes its data as properties: read them with -> and give missing ones a fallback with ??.
Additional Resources
- stdClass, in the PHP manual.
- json_decode(), in the PHP manual.
