> -----Original Message-----
> From: Hannes Magnusson [mailto:hannes.magnus...@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.willia...@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


--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to