PHP: __toString() and json_encode() not playing well together

后端 未结 5 1926
故里飘歌
故里飘歌 2021-02-07 14:31

I\'ve run into an odd problem and I\'m not sure how to fix it. I have several classes that are all PHP implementations of JSON objects. Here\' an illustration of the issue

5条回答
  •  被撕碎了的回忆
    2021-02-07 15:17

    A late answers but might be useful for others with the same problem.

    In PHP < 5.4.0 json_encode doesn't call any method from the object. That is valid for getIterator, __serialize, etc...

    In PHP > v5.4.0, however, a new interface was introduced, called JsonSerializable.

    It basically controls the behaviour of the object when json_encode is called on that object.


    Example:

    class A implements JsonSerializable
    {
        protected $a = array();
    
        public function __construct()
        {
            $this->a = array( new B, new B );
        }
    
        public function jsonSerialize()
        {
            return $this->a;
        }
    }
    
    class B implements JsonSerializable
    {
        protected $b = array( 'foo' => 'bar' );
    
        public function jsonSerialize()
        {
            return $this->b;
        }
    }
    
    
    $foo = new A();
    
    $json = json_encode($foo);
    
    var_dump($json);
    

    Outputs:

    string(29) "[{"foo":"bar"},{"foo":"bar"}]"

提交回复
热议问题