PHP json_encode类私有成员

我正在尝试对PHP中的某些对象进行JSON编码,但是我遇到了一个问题:我想对由类私有成员保存的数据进行编码。我发现这段代码通过调用类似以下的编码函数来编码此对象:


public function encodeJSON() 

    foreach ($this as $key => $value) 

    { 

        $json->$key = $value; 

    } 

    return json_encode($json); 

}

但是,只有在我要编码的对象内部不包含其他对象的情况下,这才有效。我该如何不仅对“外部”对象进行编码,还对作为对象的任何成员进行编码?


慕容708150
浏览 468回答 3
3回答

呼如林

序列化具有私有属性的对象的最佳方法是实现\ JsonSerializable接口,然后实现自己的JsonSerialize方法以返回需要序列化的数据。<?phpclass Item implements \JsonSerializable{&nbsp; &nbsp; private $var;&nbsp; &nbsp; private $var1;&nbsp; &nbsp; private $var2;&nbsp; &nbsp; public function __construct()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // ...&nbsp; &nbsp; }&nbsp; &nbsp; public function jsonSerialize()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $vars = get_object_vars($this);&nbsp; &nbsp; &nbsp; &nbsp; return $vars;&nbsp; &nbsp; }}json_encode 现在将正确序列化您的对象。
打开App,查看更多内容
随时随地看视频慕课网APP