This used to work for me but it no longer does. What’s the new / better methodology for this?
JavaScript
x
$myObj = new stdClass();
$myObj->foo->bar = "content";
$payload = json_encode($myObj);
Now I get:
JavaScript
Uncaught Error: Attempt to modify property "bar" on null
Advertisement
Answer
You need to create the nested object explicitly.
JavaScript
$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.
JavaScript
$myArr = ['foo' => ['bar' => "content"]];
$payload = json_encode($myArr);