ZF-11932: Zend_Json::encode checks for method "toJson" on objects - Zend_Json_Encoder does not.


Zend_Json::encode checks for and uses the method "toJson" on the passed object (if its an object and the method exists). This is a very handy trick. However, when used from the Json view helper, the Zend_Json_Encoder::_encodeValue() method does not make the same check.

Here is my fix (added first two lines to function):

    protected function _encodeValue(&$value)
        if (is_object($value) && method_exists($value, 'toJson')) {
            return $value->toJson();
        } else if (is_object($value)) {
            return $this->_encodeObject($value);
        } else if (is_array($value)) {
            return $this->_encodeArray($value);

        return $this->_encodeDatum($value);


This is fixed in SVN trunk and will (hopefully) be included in the next release. For more details see ZF-9521