PHP class instance to JSON

You'll need to make your variable public, in order for them to appear on json_encode().

Also, the code you're looking for is

public function toJSON(){
    return json_encode($this);
}

You're just about there. Take a look at get_object_vars in combination with json_encode and you'll have everything you need. Doing:

json_encode(get_object_vars($error));

should return exactly what you're looking for.

The comments brought up get_object_vars respect for visibility, so consider doing something like the following in your class:

public function expose() {
    return get_object_vars($this);
}

And then changing the previous suggestion to:

json_encode($error->expose());

That should take care of visibility issues.


An alternative solution in PHP 5.4+ is using the JsonSerializable interface.

class Error implements \JsonSerializable
{
    private $name;
    private $code;
    private $msg;

    public function __construct($errorName, $errorCode, $errorMSG)
    {
        $this->name = $errorName;
        $this->code = $errorCode;
        $this->msg = $errorMSG;
    }

    public function jsonSerialize()
    {
        return get_object_vars($this);
    }
}

Then, you can convert your error object to JSON with json_encode

$error = new MyError("Page not found", 404, "Unfortunately, the page does not exist");
echo json_encode($error);

Check out the example here

More information about \JsonSerializable