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_en
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"];
}
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.
public function toJSON(){
$json = array(
'name' => $this->getName(),
'code' => $this->getCode(),
'msg' => $this->getMsg(),
);
return json_encode($json);
}
Demo: http://codepad.org/mPNGD6Gv
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
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);
}