note 125963 added to jsonserializable.jsonserialize
| From: | c dot waltjen at posteo dot de | Date: | Fri, 26 Mar 2021 09:57:04 +0000 |
| Subject: | note 125963 added to jsonserializable.jsonserialize | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-219110@lists.php.net to get a copy of this message | ||
Json Serializable did not analyze the result to serialize child properties.
We have to call them manually:
<?php
class A implements JsonSerializable
{
private B $b;
public function __construct(B $b) { $this->b = $b;}
public function jsonSerialize(): array
{
return [ 'b' => $this->b->jsonSerialize()];
}
}
class B
{
private string $foo = '';
public function __construct(string $foo) { $this->foo = $foo; }
public function jsonSerialize(): array
{
return ['foo' => $this->foo];
}
}
$a = new A(new B('Hallo Welt'));
var_dump(json_encode($a));
?>
results in:
string(26) "{"b":{"foo":"Hallo Welt"}}"
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.242 (proxied: 131.117.152.84)
----
Manual Page -- http://php.net/manual/en/jsonserializable.jsonserialize.php
Edit -- https://master.php.net/note/edit/125963
Del: integrated -- https://master.php.net/note/delete/125963/integrated
Del: useless -- https://master.php.net/note/delete/125963/useless
Del: bad code -- https://master.php.net/note/delete/125963/bad+code
Del: spam -- https://master.php.net/note/delete/125963/spam
Del: non-english -- https://master.php.net/note/delete/125963/non-english
Del: in docs -- https://master.php.net/note/delete/125963/in+docs
Del: other reasons-- https://master.php.net/note/delete/125963
Reject -- https://master.php.net/note/reject/125963
Search -- https://master.php.net/manage/user-notes.php