Napoleon Napoleon - 1 year ago 145
JSON Question

How do I json encode private properties in php?

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.

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.

Answer Source

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).

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.

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download