【发布时间】:2021-09-29 13:42:39
【问题描述】:
我有以下代码。
class SomeObject implements JsonSerializable {
public string $placeholder;
public string $id;
public string $model;
public string $value;
public bool $disabled;
public bool $required;
public function jsonSerialize()
{
return get_object_vars($this);
}
}
class MainObject implements JsonSerializable
{
public string $mainName;
public SomeObject $someObject;
public function __construct() {
$this->mainName = (new ReflectionClass(MainObject::class))->getShortName();
$this->someObject = new SomeObject();
}
public function jsonSerialize()
{
return get_object_vars($this);
}
}
$main = new MainObject;
$jsonData = json_encode($main, JSON_PRETTY_PRINT);
>>> Result:
{
"mainName": "MainObject",
"someObject": []
}
我希望 MainObject 看起来像这样
{
"mainName": "MainObject",
"someObject": {
"placeholder": "",
"id": "",
"model": "",
"value": "",
"disabled": "",
"required": ""
}
}
然而,json_encode() 方法似乎只会在对象具有分配给它们的值时进行编码。如果我将 $someObject 设为关联数组,它会按预期工作。
我该怎么做?提前致谢。
【问题讨论】:
-
默认他们?
public string $placeholder = ''; -
是的!这行得通,谢谢。在不设置默认值的情况下,还有其他方法吗?