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

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

    Even if your protected variable was public instead of protected, you won't have the desired input since this will output the entire object like this:

    [{"b":{"foo":"bar"}},{"b":{"foo":"bar"}}]
    

    Instead of:

    [{"foo":"bar"},{"foo":"bar"}]
    

    It will most likely defeat your purpose, but i'm more inclined to convert to json in the original class with a default getter and calling for the values directly

    class B
    {
        protected $b = array( 'foo' => 'bar' );
    
        public function __get($name)
        {
            return json_encode( $this->$name );
        }
    }
    

    Then you could do with them whatever you desire, even nesting the values in an additional array like your class A does, but using json_decode.. it still feels somewhat dirty, but works.

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

    In the documentation there are some responses to this problem (even if i don't like most of them, serializing + stripping the properties makes me feel dirty).

提交回复
热议问题