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

From: Date: Sat, 15 May 2010 14:33:29 +0000
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
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-48299@lists.php.net to get a copy of this message
> -----Original Message----- > From: Hannes Magnusson [mailto:hannes.magnusson@gmail.com] > Sent: 15 May 2010 13:25 > To: Jared Williams > Cc: Johannes Schlüter; 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 > > 2010/5/14 Jared Williams <jared.williams1@ntlworld.com>: > >        $a = new A(); > >        echo $a->toJSONString(), "\n"; > >        $b = new B(); > >        echo $b->toJSONString(), "\n"; > > > > > $array = array(new A,new B,); > > // Does not use your toJSONString method echo json_encode($array); > Hi, Without using traits, and the current implementation... class A implements JSONSerializable { public $a = 1; protected $d = 2; private $c = 3; // have to implement this in every class function jsonSerialize() { return get_object_vars($this); } } With using traits, don't have to provide an implementation of jsonSerialize() unless want to customise the behaviour, but the current implementation will require having to implement JSONSerializable. trait Json { function toJSONString() { return json_encode($this->jsonSerialize()); } function jsonSerialize() { return get_object_vars($this); } } class A implements JSONSerializable { use Json; public $a = 1; protected $d = 2; private $c = 3; } class B implements JSONSerializable { use Json; public $a = 1; protected $d = 2; private $c = 3; function jsonSerialize() { return array('a' => $this->a, 'd' => 4); } } $r = new array(new A(), new B(), ); echo json_encode($r), "\n"; But the JSONSerialiable interface doesn't really provide no benefits over the trait, imo, so it could be eliminated leaving... trait Json { function toJSONString() { return json_encode($this->jsonSerialize()); } function jsonSerialize() { return get_object_vars($this); } } class A { use Json; public $a = 1; protected $d = 2; private $c = 3; } class B { use Json; public $a = 1; protected $d = 2; private $c = 3; function jsonSerialize() { return array('a' => $this->a, 'd' => 4); } } $r = new array(new A(), new B(), ); echo json_encode($r), "\n"; Jared

« previous php.internals (#48299) next »