note 123382 added to jsonserializable.jsonserialize
| From: | rmdundon at gmail dot com | Date: | Wed, 28 Nov 2018 18:43:59 +0000 |
| Subject: | note 123382 added to jsonserializable.jsonserialize | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-209806@lists.php.net to get a copy of this message | ||
For those who are also lazy. You cannot just include $this and expect it to work.
For example, this won't work:
<?php
class SomeClass implements JsonSerializable {
protected $partner;
function setPartner(object $partner) {
$this->partner;
}
public function jsonSerialize() {
return $this;
}
}
$foo = new SomeClass();
$too = new stdClass();
$too->test = 1;
$foo->setPartner = $too;
echo json_encode($foo); // Shows a blank object "{}"
?>
You have to define the things manually, so this will work.
<?php
class SomeClass implements JsonSerializable {
protected $partner;
function setPartner(object $partner) {
$this->partner;
}
public function jsonSerialize() {
$data['partner'] = $this->partner;
return $data;
}
}
$foo = new SomeClass();
$too = new stdClass();
$too->test = 1;
$foo->setPartner = $too;
echo json_encode($foo); // Shows {"partner":{"test":1}}
----
Server IP: 208.43.231.9
Probable Submitter: 73.1.86.12
----
Manual Page -- http://php.net/manual/en/jsonserializable.jsonserialize.php
Edit -- https://master.php.net/note/edit/123382
Del: integrated -- https://master.php.net/note/delete/123382/integrated
Del: useless -- https://master.php.net/note/delete/123382/useless
Del: bad code -- https://master.php.net/note/delete/123382/bad+code
Del: spam -- https://master.php.net/note/delete/123382/spam
Del: non-english -- https://master.php.net/note/delete/123382/non-english
Del: in docs -- https://master.php.net/note/delete/123382/in+docs
Del: other reasons-- https://master.php.net/note/delete/123382
Reject -- https://master.php.net/note/reject/123382
Search -- https://master.php.net/manage/user-notes.php