首页 > 解决方案 > 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

标签: phpclass

解决方案


推荐阅读