PHP json_encode类私有成员 [英] PHP json_encode class private members
问题描述
我正在尝试对PHP中的某些对象进行JSON编码,但是我遇到了一个问题:我想对由类私有成员保存的数据进行编码. 我发现这段代码通过调用诸如以下的编码函数来对该对象进行编码:
I'm trying to JSON encode some objects in PHP, but I'm facing a problem: I want to encode data which is kept by a class private members. I found this piece of code to encode this object by calling an encode function like:
public function encodeJSON()
{
foreach ($this as $key => $value)
{
$json->$key = $value;
}
return json_encode($json);
}
但是,这仅在要编码的对象内部不包含其他对象的情况下才有效.我该如何不仅对外部"对象进行编码,而且还要对作为对象的任何成员进行编码?
However, this only works if the object I want to encode does not contain other objects inside, which is the case. How can I do to encode not only the "outer" object, but encode as well any members that are objects too?
推荐答案
使用私有属性序列化对象的最佳方法是实现\ JsonSerializable接口,然后实现自己的JsonSerialize方法以返回需要序列化的数据
The best method to serialize an object with private properties is to implement the \JsonSerializable interface and then implement your own JsonSerialize method to return the data you require to be serialized.
<?php
class Item implements \JsonSerializable
{
private $var;
private $var1;
private $var2;
public function __construct()
{
// ...
}
public function jsonSerialize()
{
$vars = get_object_vars($this);
return $vars;
}
}
json_encode
现在将正确序列化您的对象.
json_encode
will now serialize your object correctly.
这篇关于PHP json_encode类私有成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!