【问题标题】:PHP stdClass nested propertiesPHP stdClass 嵌套属性
【发布时间】:2020-12-03 02:01:13
【问题描述】:

这曾经对我有用,但现在不再有用。对此有什么新的/更好的方法?

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

现在我明白了:

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

【问题讨论】:

  • 这是升级到 PHP8 后发生的事情吗?

标签: php stdclass


【解决方案1】:

您需要显式创建嵌套对象。

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

但如果您只是创建 JSON,使用关联数组而不是对象会更简单。它们可以很容易地写成文字。

$myArr = ['foo' => ['bar' => "content"]];
$payload = json_encode($myArr);

【讨论】:

    猜你喜欢
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多