将类属性返回为JSON

时间:2013-04-03 23:20:48

标签: php

我正在尝试将php中的某些属性编码为JSON,但我所有的方法都返回{}

这是我的代码,我哪里错了?

感谢。

    <?php

    class Person  
    {  
        private $_photo;  
        private $_name;  
        private $_email;  


        public function __construct($photo, $name, $email)  
        {  
    $this->_photo = $photo;  
            $this->_name = $name;  
            $this->_email = $email;  

        }  



       public function getJsonData() {
          $json = new stdClass;
          foreach (get_object_vars($this) as $name => $value) {
             $this->$name = $value;
          }
          return json_encode($json);
       }


    }  


    $person1 = new Person("mypicture.jpg", "john doe", "doeman@gmail.com");  

    print_r( $person1->getJsonData() );

2 个答案:

答案 0 :(得分:2)

那是因为您没有使用$ json变量,而是使用$ this-&gt; $ name。您指的是哪个$?你没有使用我所看到的$ json变量。

class Person  
{  
    private $_photo;  
    private $_name;  
    private $_email;  


    public function __construct($photo, $name, $email)  
    {  
$this->_photo = $photo;  
        $this->_name = $name;  
        $this->_email = $email;  

    }  



   public function getJsonData() {
      //I'd make this an array
      //$json = new stdClass;
      $json = array();

      foreach (get_object_vars($this) as $name => $value) {
         //Here is my change
         //$this->$name = $value;
         $json[$name] = $value
      }
      return json_encode($json);
   }


}  


$person1 = new Person("mypicture.jpg", "john doe", "doeman@gmail.com");  

print_r( $person1->getJsonData() );

希望它能解决你的问题。我就是这样做的。

答案 1 :(得分:0)

在类中实现JsonSerializable接口,从PHP 5.4开始。