0

I created a PHP class with private properties. When creating new instance from it, it displays an empty json, only visible when calling the getters. How I can display or build a toString method to return class as object? Also I tried to use serializing it works but it displays an awkward characters even after 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
rami-sf
  • 119
  • 1
  • 10
  • It's because they are private, I guess and only accessible within class and not outside of class at any way. – Rahul Feb 06 '20 at 12:37
  • Yes I know, I want to keep them private to keep code clean but I need to send them to client. – rami-sf Feb 06 '20 at 12:39

0 Answers0