- get_object_vars: documentation ( source)
- json_encode: documentation ( source)
<?php
class MyError 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);
// or
return [
'name' => $this->name,
'code' => $this->code,
'msg' => $this->msg
];
}
}
$error = new MyError("Page not found", 404, "Unfortunately, the page does not exist");
echo json_encode($error);