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

后端 未结 5 2027
故里飘歌
故里飘歌 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:25

    You're right the __toString() for the class B is not being called, because there is no reason to. So to call it, you can use a cast

    class A
    {
        protected $a;
    
        public function __construct()
        {
            $this->a = array( (string)new B, (string)new B );
        }
    
        public function __toString()
        {
            return json_encode( $this->a );
        }
    }
    

    Note: the (string) cast before the new B's ... this will call the _toString() method of the B class, but it won't get you what you want, because you will run into the classic "double encoding" problems, because the array is encoded in the B class _toString() method, and it will be encoded again in the A class _toString() method.

    So there is a choice of decoding the result after the cast, ie:

     $this->a = array( json_decode((string)new B), json_decode((string)new B) );
    

    or you're going to need to get the array, by creating a toArray() method in the B class that returns the straight array. Which will add some code to the line above because you can't use a PHP constructor directly (you can't do a new B()->toArray(); ) So you could have something like:

    $b1 = new B;
    $b2 = new B;
    $this->a = array( $b1->toArray(), $b2->toArray() );
    

提交回复
热议问题