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