PHP Bug: json_encode() misleading warning on object with private properties

I have found a peculiar issue with PHP’s json_encode() function.

If you have an instance object with private properties and use json_encode() it will give you a very misleading warning.

class ExampleObject {
    private $privateProperty;
    ...
}
$obj = new ExampleObject();
json_encode($obj);

results in

Warning: json_encode() … recursion detected …

There are two workarounds in the comments for the function at php.net but this is simply a PHP bug as far as I am concerned.

Leave a Reply