php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #46215 json_encode mutates its parameter and has some class-specific state
Submitted: 2008-10-02 00:46 UTC Modified: 2008-10-02 03:43 UTC
From: todd at amiestreet dot com Assigned: felipe (profile)
Status: Closed Package: JSON related
PHP Version: 5.3.0alpha2 OS: linux x86 (32 bit)
Private report: No CVE-ID: None
 [2008-10-02 00:46 UTC] todd at amiestreet dot com
Description:
------------
The second time json_encode is called on objects of a given class, the private variables of the first *instance* serialize as null.

Also, print_r produces different output after json_encode is called on an object.

Reproduce code:
---------------
<?php
class Blah {
    protected $a = array();
}

$a = new Blah; $b = new Blah;
header('Content-type: text/plain');

print ($s1 = serialize($a)) . "\n";
print "--------------------------------------------------\n";

// Comment out either of the following lines and all is well

$print_a1 = print_r($a, true);
$junk = json_encode($a);
$print_a2 = print_r($a, true);
$junk = json_encode($b); // <-- unrelated variable!!!

print ($s2 = serialize($a)) . "\n\n";

print "\n\n" . $print_a1 . "\n" . $print_a2;
?>

Expected result:
----------------
serialize() called before and after the second json_encode should return the exact same result, given they're called on the same unmodified variable. ($s1 and $s2 should be equal but aren't)

$print_a and $print_b should also be equal, but calling json_encode causes print_r to mistakenly detect recursion.

Actual result:
--------------
O:4:"Blah":1:{s:4:"�*�a";a:0:{}}
--------------------------------------------------
O:4:"Blah":1:{s:4:"�*�a";N;}



Blah Object
(
    [a:protected] => Array
        (
        )

)

Blah Object
(
    [a:protected] => Array
 *RECURSION*
)


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-10-02 03:43 UTC] felipe@php.net
This bug has been fixed in CVS.

Snapshots of the sources are packaged every three hours; this change
will be in the next snapshot. You can grab the snapshot at
http://snaps.php.net/.
 
Thank you for the report, and for helping us make PHP better.

Fixed in 5.2, 5.3 and HEAD.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Nov 21 09:01:32 2024 UTC