php - PHP类私有属性转换为json时为空
问题描述
我创建了一个带有私有属性的 PHP 类。从它创建新实例时,它显示一个空 json,仅在调用 getter 时可见。如何显示或构建 toString 方法以将类作为对象返回?我也尝试使用序列化它可以工作,但即使在 json_encode 之后它也会显示一个尴尬的字符。
class Role
{
private $id;
private $code;
private $name;
private $description;
public function __construct($id, $code, $name, $description)
{
$this->id = $id;
$this->code = $code;
$this->name = $name;
$this->description = $description;
}
public function __setId($id)
{
$this->id = $id;
}
public function __getId()
{
return $this->id;
}
public function __setCode($code)
{
$this->code = $code;
}
public function __getCode()
{
return $this->code;
}
public function __setName($name)
{
$this->name = $name;
}
public function __getName()
{
return $this->name;
}
public function __setDescription($description)
{
$this->description = $description;
}
public function __getDescription()
{
return $this->description;
}
}
$role = new Role(1, "ROLE_ADMIN", "ADMIN ROLE", "Only For Admins");
echo json_encode($role); // it displays {} empty json
解决方案
推荐阅读
- r - 如何将不同长度的字符向量绑定到数据框中?
- tensorflow - tensorflow 2.0 中的多标签分割
- java - 多线程代码对许多工作人员来说太慢,但对少数工作人员来说速度很快
- java - 在java中,输入文本并将它们放入二维字符数组中
- javascript - Angular8 - 将模型作为带有单独字段的发布请求发送
- python - 动态分配唯一值 - Python
- go - golang中的类型转换
- c# - 与不同域中的 WCF 服务通信
- vba - Outlook 电子邮件对话的最后一个元素不会触发 VBA 中的 Application_ItemLoad 事件
- matlab - 我可以使用不同的循环来执行此操作,以及如何使其成为函数?