douhang5460 2017-10-05 11:14
浏览 83
已采纳

如何使用PHP / Json对象填充另一个类函数

so I have this JSON object, which I have converted into a PHP object, for example I can use $apiobject->Response->DataItems and get a response.

This is stored in a class called returnjsonObject with a public function called getJsonObject.

In the same file how can I populate another class using the data from this $apiobject into something like:

class Response
 {
   public $StatusCode;
 }

Then how can I for example echo out $StatusCode

Here is part of my file:

class Response
{
    public $StatusCode; //*I want this to equal $apiobject->Response->DataItems*
}

class returnjsonObject{
    public function getJsonObject()
    {

            echo"<pre>";
            $apiobject = json_decode($response);
            var_dump($apiobject->Response->DataItems);
            echo"<pre>";
    }

I've heard of using $this but I have to admit I don't understand it.

tl;dr I need to use $apiobject to populate $StatusCode using $apiobject->Response->DataItems

Hope you understand my question :-)

  • 写回答

2条回答 默认 最新

  • dongshanni1611 2017-10-05 11:47
    关注

    You can use setter and getter

    class Response{
    
       public $StatusCode;
    
        /**
        ...... 
    
        */
    
    
      public function __construct($attributes = Array()){
        // Apply provided attribute values
        foreach($attributes as $field=>$value){
          $this->$field = $value;
        }
      }
    
      function __set($name,$value){
        if(method_exists($this, $name)){
          $this->$name($value);
        }
        else{
          // Getter/Setter not defined so set as property of object
          $this->$name = $value;
        }
      }
    
      function __get($name){
        if(method_exists($this, $name)){
          return $this->$name();
        }
        elseif(property_exists($this,$name)){
    
          return $this->$name;
        }
        return null;
      }
    }
    
    $DataItems =$apiobject->DataItems;
    $response = new Response($DataItems); 
    echo $response->StatusCode;
    

    Code not tested though. Learn more here. http://www.beaconfire-red.com/epic-stuff/better-getters-and-setters-php

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

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用