note 111263 added to jsonserializable.jsonserialize

From: Date: Thu, 31 Jan 2013 16:17:42 +0000
Subject: note 111263 added to jsonserializable.jsonserialize
Groups: php.notes 
Request: Send a blank email to php-notes+get-193465@lists.php.net to get a copy of this message
A good example on when you would use functionality like this is when working with objects. json_encode() will take a DateTime and convert it to: { "date":"2013-01-31 11:14:05", "timezone_type":3, "timezone":"America\/Los_Angeles" } This is great when working with PHP, but if the Date is being read by Java. The Java date parser doesn't know what to do with that. But it does know what to do with the ISO8601 format... <?php date_default_timezone_set('America/Los_Angeles'); class Fruit implements JsonSerializable { public $type = 'Apple', $lastEaten = null; public function __construct() { $this->lastEaten = new DateTime(); } public function jsonSerialize() { return [ 'type' => $this->type, 'lastEaten' => $this->lastEaten->format(DateTime::ISO8601) ]; } } echo json_encode(new Fruit()); //which outputs: {"type":"Apple","lastEaten":"2013-01-31T11:17:07-0500"} ?> ---- Server IP: 69.147.83.199 Probable Submitter: 74.143.144.100 ---- Manual Page -- http://php.net/manual/en/jsonserializable.jsonserialize.php Edit -- https://master.php.net/note/edit/111263 Del: integrated -- https://master.php.net/note/delete/111263/integrated Del: useless -- https://master.php.net/note/delete/111263/useless Del: bad code -- https://master.php.net/note/delete/111263/bad+code Del: spam -- https://master.php.net/note/delete/111263/spam Del: non-english -- https://master.php.net/note/delete/111263/non-english Del: in docs -- https://master.php.net/note/delete/111263/in+docs Del: other reasons-- https://master.php.net/note/delete/111263 Reject -- https://master.php.net/note/reject/111263 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#193465) next »