如何获取使用getter和setter的类的JSON表示?

时间:2018-05-28 19:45:39

标签: php json object entity getter-setter

我不熟悉getter和设置,并希望开始尝试它们。我看到如何检索单个属性,但是如何以JSON格式(如{"firstField":321, "secondField":123})接收检索属性或所有属性。我已尝试public function get(){ return $this;}甚至public function getJson(){return json_encode($this);},但只是获得了空JSON。

PS。设置者中的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

1 个答案:

答案 0 :(得分:0)

受到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
        ];
    }
}