Skip to content
Advertisement

PHP stdClass nested properties

This used to work for me but it no longer does. What’s the new / better methodology for this?

$myObj = new stdClass();
$myObj->foo->bar = "content";
$payload = json_encode($myObj);

Now I get:

Uncaught Error: Attempt to modify property "bar" on null

Advertisement

Answer

You need to create the nested object explicitly.

$myObj = new StdClass;
$myObj->foo = new StdClass;
$myObj->foo->bar = "content";
$payload = json_encode($myObj);

But if you’re just creating JSON, it would be simpler to use associative arrays instead of objects. They can be written as literals easily.

$myArr = ['foo' => ['bar' => "content"]];
$payload = json_encode($myArr);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement