【问题标题】:How do I get a JSON representation of a class which uses getters and setters?如何获得使用 getter 和 setter 的类的 JSON 表示?
【发布时间】:2018-05-28 19:45:38
【问题描述】:

我是 getter 和设置的新手,并想开始尝试它们。我了解如何检索单个属性,但如何以 JSON 格式接收检索属性或所有属性,例如 {"firstField":321, "secondField":123}。我试过public function get(){ return $this;},甚至public function getJson(){return json_encode($this);},但只是得到空的JSON。

附言。设置器中的return $this; 是拼写错误还是提供了一些价值?

<?php
class MyClass {
  private $firstField;
  private $secondField;

  public function __get($property) {
    if (property_exists($this, $property)) {
      return $this->$property;
    }
  }

  public function __set($property, $value) {
    if (property_exists($this, $property)) {
      $this->$property = $value;
    }

    return $this;
  }
}
?>

参考https://stackoverflow.com/a/4478690/1032531

【问题讨论】:

  • 实现JsonSerializable接口
  • return $this 这不是拼写错误,它使方法可链接。
  • @NobbyNobbs 感谢链式评论。仍在调查php.net/manual/en/jsonserializable.jsonserialize.php。看起来工作量很大,我希望 getter 和 setter 实际上是一件好事。我知道有些人不喜欢魔术方法,但即使我不使用它们,问题也是一样的。
  • 为什么你认为 JsonSerializable 的实现看起来需要做很多工作?您只需要实现一种方法,它只返回像这样的 assoc 数组 ['prop1'=&gt;$this-&gt;prop1, 'prop2'=&gt;$this-&gt;prop2]
  • @NobbyNobbs 我不认为这是很多工作(不再)。它工作得很好。谢谢!

标签: php json object entity getter-setter


【解决方案1】:

深受 NobbyNobbs 的启发。

abstract class Entity implements \JsonSerializable
{
    public function __get($property) {
        if (property_exists($this, $property)) return $this->$property;
        else throw new \Exception("Property '$property' does not exist");
    }

    public function __set($property, $value) {
        if (!property_exists($this, $property)) throw new \Exception("Property '$property' is not allowed");
        $this->$property = $value;
        return $this;
    }
}

class Something extends Entity
{
    protected $name, $id, $data=[];

    public function jsonSerialize()
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'data' => $this->data
        ];
    }
}

【讨论】:

    猜你喜欢
    • 2019-11-26
    • 2012-03-12
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    相关资源
    最近更新 更多