【问题标题】:How can I populate another class function using PHP/Json object如何使用 PHP/Json 对象填充另一个类函数
【发布时间】:2017-10-05 11:14:25
【问题描述】:

所以我有这个 JSON 对象,我已将其转换为 PHP 对象,例如我可以使用 $apiobject->Response->DataItems 并获得响应。

这存储在一个名为 returnjsonObject 的类中,并带有一个名为 getJsonObject 的公共函数。

在同一个文件中,如何使用 $apiobject 中的数据将另一个类填充到类似的内容中:

class Response
 {
   public $StatusCode;
 }

那么我该如何例如回显 $StatusCode

这是我文件的一部分:

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>";
    }

我听说过使用 $this 但我不得不承认我不明白。

tl;dr 我需要使用 $apiobject 来填充 $StatusCode 使用 $apiobject->Response->DataItems

希望你能理解我的问题:-)

【问题讨论】:

标签: php json class object


【解决方案1】:

你可以使用 setter 和 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;

代码没有经过测试。在这里了解更多。 http://www.beaconfire-red.com/epic-stuff/better-getters-and-setters-php

【讨论】:

    【解决方案2】:

    我会首先像这样在$apiobject 中设置Response 类中的所有属性

    <?php
    
    class Response {
    
    public $StatusCode;
    /* more attributes
    ...
    */
    public $Name
    
    } //end of Response class
    

    然后实例化Response类并设置属性

    $response = new Response();
    
    
      $response->StatusCode =$apiobject->DataItems->StatusCode;
      $response->Name=$apiobject->DataItems->Name;
    
    /* Set all other properties
    .......
    */
    
    echo $respose->StatusCode; //output status code
    

    注意:您使用$this 来引用当前类中的函数或属性。即

    Class Example {
    public $name;
    public function getThatName(){
     return $this->name; //we make reference to property `$name`
    }
    }
    

    $this 只能在ClassObject 中用于引用属性或函数本身。

    你不能这样做。

    $example = new Example();
    $this->name; //Wrong because you are not in `Example` class
    

    【讨论】:

    • 有没有其他方法可以做到这一点,我有大约 30 个类,大约有 10 个功能?
    • 你可以使用getter和setter来实现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多