PHP class instance to JSON

后端 未结 5 2156
庸人自扰
庸人自扰 2020-12-08 09:28

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

5条回答
  •  庸人自扰
    2020-12-08 10:15

    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

提交回复
热议问题