ZF-4682: Add support for a toJson() method to Zend_Json::encode()


Zend_Json::encode() should support reading a Json string when an object is passed. Proposed patch:

public static function encode($valueToEncode, $cycleCheck = false, $options = array())
    if (is_object($valueToEncode) && method_exists($valueToEncode, 'toJson')) {
        return $valueToEncode->toJson();
    if (function_exists('json_encode') && self::$useBuiltinEncoderDecoder !== true) {
        return json_encode($valueToEncode);

    require_once 'Zend/Json/Encoder.php';
    return Zend_Json_Encoder::encode($valueToEncode, $cycleCheck, $options);


Resolved in revision 12081

Changing issues in preparation for the 1.7.0 release.

This functionality would be far more useful if it applied to objects located anywhere in a graph being serialized, rather than just the Zend_Json::encode() argument itself. I was surprised to find, for example, that encode() calls my toJson() method when I serialize a single instance but not when I serialize an array of instances. It really should be defined recursively like the rest of the encoding process.

I'm guessing this would introduce a difference in the capabilities of the built-in and native encoders, but I think it would be worth it.

I agree, this functionality is pretty useless unless it can be applied to objects within an array.