PHP class instance to JSON
Asked Answered
J

5

45

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}

Jelks answered 27/3, 2012 at 19:24 Comment(1)
prob wasn't around at the time of writing this, but if you are now using >5.4 you can have your class implement JsonSerializableResponsive
J
51

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.

Janus answered 27/3, 2012 at 19:26 Comment(4)
I tried this before but it returned {}. Guess I did something wrong before, thanks man!Jelks
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 varsTemperature
json_encode(get_object_vars($error));will display public members, no privates.Sterlingsterlitamak
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.Janus
A
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

Aestheticism answered 18/7, 2016 at 17:43 Comment(1)
Notice that the name of the class should've been MyError as the second code-snippet creates a new instance of MyError and not ErrorTacet
S
10

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);
}
Scruple answered 27/3, 2012 at 19:29 Comment(1)
I like this as I don't know of a way for get_object_vars to exclude properties you don't want to serialize.Cascara
W
7
public function toJSON(){
    $json = array(
        'name' => $this->getName(),
        'code' => $this->getCode(),
        'msg' => $this->getMsg(),
    );

    return json_encode($json);
}

Demo: http://codepad.org/mPNGD6Gv

Wald answered 27/3, 2012 at 19:26 Comment(0)
G
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"];       
}
Gerund answered 16/11, 2019 at 20:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.