PHP类实例到JSON

Rei*_*ard 36 php json encode object

我正在尝试以JSON格式回显对象的内容.我对PHP很缺乏经验,我想知道是否有预定义的函数来执行此操作(如json_encode())或者您是否必须自己构建字符串?谷歌搜索"PHP对象到JSON",我只是找到垃圾.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要JSON返回的内容:

{name:"$ name var的内容",代码:1001,msg:执行请求时出错}

cle*_*ond 40

你就在那里.看看get_object_vars与json_encode结合使用,您就拥有了所需的一切.这样做:

json_encode(get_object_vars($error));
Run Code Online (Sandbox Code Playgroud)

应该准确地返回您正在寻找的东西.

这些评论提出了get_object_vars对可见性的尊重,因此请考虑在您的课程中执行以下操作:

public function expose() {
    return get_object_vars($this);
}
Run Code Online (Sandbox Code Playgroud)

然后将之前的建议更改为:

json_encode($error->expose());
Run Code Online (Sandbox Code Playgroud)

这应该照顾可见性问题.


Man*_*y S 29

PHP 5.4+中的另一种解决方案是使用JsonSerializable接口.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用json_encode将错误对象转换为JSON

$error = new MyError("Page not found", 404, "Unfortunately, the page does not exist");
echo json_encode($error);
Run Code Online (Sandbox Code Playgroud)

看看这里的例子

有关\ JsonSerializable的更多信息


Mad*_*iha 9

您需要将变量公开,以便显示它们json_encode().

此外,您正在寻找的代码是

public function toJSON(){
    return json_encode($this);
}
Run Code Online (Sandbox Code Playgroud)


Nea*_*eal 5

public function toJSON(){
    $json = array(
        'name' => $this->getName(),
        'code' => $this->getCode(),
        'msg' => $this->getMsg(),
    );

    return json_encode($json);
}
Run Code Online (Sandbox Code Playgroud)

演示:http://codepad.org/mPNGD6Gv