47

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}

1
  • 8
    prob wasn't around at the time of writing this, but if you are now using >5.4 you can have your class implement JsonSerializable Commented Apr 3, 2014 at 7:47

5 Answers 5

55

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I tried this before but it returned {}. Guess I did something wrong before, thanks man!
AFAIK get_object_vars also takes into consideration the scope where it's called, so if you call it from a method inside the object, you will also have access to the private vars
json_encode(get_object_vars($error));will display public members, no privates.
Yeah, get_object_vars respects visibility, so you'll likely need to add a "expose" method or something similar to handle that. I'll add this suggestion to the answer.
48

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

1 Comment

Notice that the name of the class should've been MyError as the second code-snippet creates a new instance of MyError and not Error
11

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);
}

2 Comments

I like this as I don't know of a way for get_object_vars to exclude properties you don't want to serialize.
This should be the top answer. So many others are trying to reverse engineer the default behavior of public vs. private properties in the object. From the PHP docs on json_encode: "by default only publicly visible properties will be included".
7
public function toJSON(){
    $json = array(
        'name' => $this->getName(),
        'code' => $this->getCode(),
        'msg' => $this->getMsg(),
    );

    return json_encode($json);
}

Demo: http://codepad.org/mPNGD6Gv

Comments

0

In Linux, the following will write the value of a given class entry in a file ~/.config/scriptname/scriptname.conf, create the file if it doesn't exist, and otherwise read and set back the class value at loading:

/* Example class */
class flag {
  static $COLORSET = ["\033[34;1m","\033[31;1m"];
}
/* Retrieve and set back values, otherwise create config file with the defined value --------------------------------------------------*/
if (!is_file($_SERVER["HOME"]."/.config/".$_SERVER["SCRIPT_NAME"]."/".$_SERVER["SCRIPT_NAME"].".conf")){
    @mkdir($_SERVER["HOME"]."/.config/".$_SERVER["SCRIPT_NAME"]);
    @file_put_contents($_SERVER["HOME"]."/.config/".$_SERVER["SCRIPT_NAME"]."/".$_SERVER["SCRIPT_NAME"].".conf",json_encode(["COLORSET"=>flag::$COLORSET]));
} else {
    flag::$COLORSET = json_decode(file_get_contents($_SERVER["HOME"]."/.config/".$_SERVER["SCRIPT_NAME"]."/".$_SERVER["SCRIPT_NAME"].".conf"), true)["COLORSET"];       
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.