Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

JSON Objects

When encoding PHP objects as JSON, all public properties of that object will be encoded in a JSON object.

JSON does not allow object references, so care should be taken not to encode objects with recursive references. If you have issues with recursion, Zend_Json::encode() and Zend_Json_Encoder::encode() allow an optional second parameter to check for recursion; if an object is serialized twice, an exception will be thrown.

Decoding JSON objects poses an additional difficulty, however, since Javascript objects correspond most closely to PHP's associative array. Some suggest that a class identifier should be passed, and an object instance of that class should be created and populated with the key/value pairs of the JSON object; others feel this could pose a substantial security risk.

By default, Zend_Json will decode JSON objects as associative arrays. However, if you desire an object returned, you can specify this:

// Decode JSON objects as PHP objects
$phpNative Zend_Json::decode($encodedValueZend_Json::TYPE_OBJECT);

Any objects thus decoded are returned as StdClass objects with properties corresponding to the key/value pairs in the JSON notation.

The recommendation of Zend Framework is that the individual developer should decide how to decode JSON objects. If an object of a specified type should be created, it can be created in the developer code and populated with the values decoded using Zend_Json.

Zend Framework