如何在php中json编码私有属性? [英] How do I json encode private properties in php?

查看:83
本文介绍了如何在php中json编码私有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用准则2和zend框架1.11.在教义2中不鼓励使用公共属性,因此我将实体属性设为私有.但是,我刚刚了解到Zend_Json :: encode()和json_encode()不会看到私有/受保护的属性,因此,不会在输出中添加它们.

I am working with doctrine 2 and zend framework 1.11. Public properties are discouraged in Doctrine 2, so I made my entity properties private. However I have just learned that Zend_Json::encode() and json_encode() will not see private / protected properties and thus, not add them in the their output.

因此,当我同时使用var_dump和var_dump时,会得到一个空集,例如string(4)"[{}]".

Therefore when I use either, and var_dump, I get an empty set eg string(4) "[{}]".

事实证明,我必须编写自己的函数来进行编码.我希望有人有一个可以代替的解决方案.

It turns out I have to write my own function to do the encoding. I was hoping someone has a solution that I can use instead.

推荐答案

将成员变量设为私有的全部目的是为了防止它们对任何外部代码可见(序列化是一个例外,因为整个对象都需要在会话之间恢复).

The entire point of having member variables as private is to prevent them from being visible to any external code (serialize is an exception because the entire object will need to be restored between sessions).

您可能应该使用方法"encode"创建"enable"接口,而不是json_encoding该对象.这将返回此对象所需的任何成员的json编码的字符串.这给了您更多的控制权,因为您可以选择要序列化的成员,而不是序列化所有成员,甚至可以对它们执行操作以序列化其他数据.

Instead of json_encoding this object, you should perhaps create an interface "encodeable" with a method "encode." This will return a json-encoded string of any of the members required by this object. This gives you additional control because instead of serializing all members, you can choose the ones you want to serialize and even perform operations on them to serialize other data.

实际上,您可以实施 JsonSerializable 接口,该接口可直接与json_encode.

Actually you can imlement the JsonSerializable interface which works directly with json_encode.

class MyClass implements \JsonSerializable
{
    public function jsonSerialize()
    {
        return get_object_vars($this);
    }
}

$myObject = new MyClass();
echo json_encode($myObject);

这篇关于如何在php中json编码私有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆