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
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