假设我们有一个简单的对象可以使用嵌套对象进行序列化:
class User implements \JsonSerializable
{
private $name;
private $email;
private $address;
public function jsonSerialize()
{
return [
'name' => $this->name,
'email' => $this->email,
'address' => $this->address
];
}
}
嵌套对象:
class Address implements \JsonSerializable
{
private $city;
private $state;
public function jsonSerialize()
{
return [
'city' => $this->city,
'state' => $this->state
];
}
}
We use json_encode()
序列化,这将在本机使用JsonSerialized::jsonSerialize() http://php.net/manual/en/jsonserializable.jsonserialize.php:
$json = json_encode($user);
If $name
and $state
为空,如何得到这个:
{
"email": "[email protected] /cdn-cgi/l/email-protection",
{
"city": "Paris"
}
}
而不是这个:
{
"name": null,
"email": "[email protected] /cdn-cgi/l/email-protection",
{
"city": "Paris",
"state": null
}
}