Reinard Reinard - 1 year ago 124
JSON Question

PHP class instance to JSON

I'm trying echo the contents of an object in a JSON format. I'm quite unexperienced with PHP and I was wondering if there is a predefined function to do this (like json_encode()) or do you have to build the string yourself?
When Googling "PHP object to JSON", I'm just finding garbage.

class Error {
private $name;
private $code;
private $msg;
public function __construct($ErrorName, $ErrorCode, $ErrorMSG){
$this->name = $ErrorName;
$this->code = $ErrorCode;
$this->msg = $ErrorMSG;
public function getCode(){
return $this->code;
public function getName(){
return $this->name;
public function getMsg(){
return $this->msg;
public function toJSON(){
$json = "";

return json_encode($json);

What I want toJSON to return:

{ name: "the content of $name var", code : 1001, msg : error while
doing request}

Answer Source

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:


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:


That should take care of visibility issues.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download