The point is that json_encode will automatically call and use the return of jsonSerialize() no matter WHERE you serialize the object.
This is great when you're JSONifying objects when working with frameworks etc. - Davey On May 13, 2010, at 6:29 PM, Jared Williams wrote: > > >> -----Original Message----- >> From: Johannes Schlüter [mailto:johan...@schlueters.de] >> Sent: 13 May 2010 20:47 >> To: Jared Williams >> Cc: 'Pierre Joye'; 'Stanislav Malyshev'; 'Sara Golemon'; 'PHP >> Internals' >> Subject: RE: [PHP-DEV] Re: [PHP-CVS] svn: /php/php-src/trunk/ >> NEWS ext/json/json.c ext/json/php_json.h > ext/json/tests/serialize.phpt >> >> On Thu, 2010-05-13 at 20:27 +0100, Jared Williams wrote: >>> Hi, >>> Keep thinking with what is in php.next that interfaces >> seem overkill? >>> >>> Doesn't >>> >>> trait JSON >>> { >>> function toJSONString() >>> { >>> return json_encode(get_object_vars($this)); >>> } >>> } >> >>> class A >>> { >>> use JSON; >>> >>> public $a = 1; >>> protected $b = 2; >>> private $c = 3; >>> } >> >> No. The goal is to allow json_encode($foo); to do what makes >> sense in the case. You might re-use the implementation by >> implementing it using traits, but tha's a different problem >> than what this interface solves. >> >> johannes >> > > Still not seeing the point of the interface. > > <?php > > trait Json > { > function toJSONString() > { > return json_encode($this->jsonSerialize()); > } > > protected function jsonSerialize() > { > return get_object_vars($this); > } > } > > class A > { > use Json; > > public $a = 1; > protected $b = 2; > private $c = 3; > } > > class B > { > use Json; > > public $a = 1; > protected $b = 2; > private $c = 3; > > protected function jsonSerialize() > { > return array('a' => $this->a, 'd' => 4); > } > } > > $a = new A(); > echo $a->toJSONString(), "\n"; > $b = new B(); > echo $b->toJSONString(), "\n"; > > Jared > > > -- > PHP Internals - PHP Runtime Development Mailing List > To unsubscribe, visit: http://www.php.net/unsub.php > -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php