doushen8391 2013-04-03 23:20
浏览 13
已采纳

将类属性返回为JSON

I'm trying to encode some properties in a class in php to JSON but all my method is returning is {}

Here's my code, where am I going wrong?

Thanks.

    <?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条回答 默认 最新

  • dongqiao8421 2013-04-03 23:26
    关注

    That's is because you are not using the $json variable but instead you are using $this->$name. Which $this are you refering too? You aren't using the $json variable from what I am seeing.

    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() );
    

    Hope it solves you problem. That's how I would do it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭