1

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
1
  • Was this something that happened after upgrading to PHP8? Commented Jan 11, 2022 at 9:19

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.