Skip to main content

How to Read Properties of a stdClass Object in PHP

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
$<object>-><property>
$<object>-><property> ?? <fallback>
PartWhat 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:

main.php, which decodes a JSON object with name Ada and role admin, and echoes get_class($user), $user->name and $user->email with the fallback no email.

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​

Terminal
php main.php
Output
stdClass
Ada
no email

A zsh terminal where php main.php prints stdClass, Ada and 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​

MistakeWhat happensDo this instead
Reading it like an array, as in $user['name']Fatal error: Uncaught Error: Cannot use object of type stdClass as arrayUse $user->name
Reading a missing property without ??Warning: Undefined property: stdClass::$email and nullAdd ?? 'default'
Expecting an array from json_decodeYou get an object unless you ask for an arrayPass true as the second argument

Troubleshooting​

SymptomLikely causeFix
Cannot use object of type stdClass as arraySquare brackets on an objectSwitch to ->
Undefined property: stdClass::$…The JSON had no such keyCheck 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​