|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2011-08-23 15:31 UTC] roan dot kattouw at gmail dot com
Description:
------------
If you have an object with numeric string keys such as "1", serialize() and unserialize() will not round-trip cleanly: if $foo = array("1" =>"foo"), unserialize(serialize($foo)) will be array(1=>"foo").
I'm not actually sure this is a bug in serialize()/unserialize(); it seems to be a bug in json_decode() instead. Somewhat counter-intuitively, arrays or objects with numeric string keys are really hard to produce. Constructs like array("1"=>"foo") or even $s = "1"; $arr[$s] = "foo"; produce an array with int(1) as the key rather than string("1"). The same is true for objects. The only thing that produces numeric string keys, AFAIK, is json_decode().
A very related bug, and the reason I noticed this in the first place, is that if you have an object with numeric keys and set $s = "2" , $obj->{$s} will not return the value for key 2. Worse, it seems there's no way to access the value short of casting the object to an array and using $arr[2].
Related bugs have been filed and closed, but they don't seem to have addressed this issue properly:
#48557: patch applied to 5.2 and 5.3; I found this bug in 5.4
#48171: basically the same problem, marked as bogus referring to #48959 , which is about arrays not objects. It claims to have been documented in the manual, but again that refers to arrays not objects
Test script:
---------------
<?php
error_reporting(E_ALL);
$s = "2";
$i = 2;
$foo = json_decode('{"1":"foo","2":"bar"}');
$ser = serialize($foo);
$bar = unserialize($ser);
var_dump($foo);
var_dump($ser);
var_dump($bar);
var_dump($foo->{$s});
var_dump($foo->{$i});
var_dump($bar->{$s});
var_dump($bar->{$i});
Expected result:
----------------
object(stdClass)#1 (2) {
["1"]=>
string(3) "foo"
["2"]=>
string(3) "bar"
}
string(55) "O:8:"stdClass":2:{s:1:"1";s:3:"foo";s:1:"2";s:3:"bar";}"
object(stdClass)#2 (2) {
["1"]=>
string(3) "foo"
["2"]=>
string(3) "bar"
}
string(3) "bar"
string(3) "bar"
string(3) "bar"
string(3) "bar"
Actual result:
--------------
object(stdClass)#1 (2) {
["1"]=>
string(3) "foo"
["2"]=>
string(3) "bar"
}
string(55) "O:8:"stdClass":2:{s:1:"1";s:3:"foo";s:1:"2";s:3:"bar";}"
object(stdClass)#2 (2) {
[1]=>
string(3) "foo"
[2]=>
string(3) "bar"
}
string(3) "bar"
string(3) "bar"
Notice: Undefined property: stdClass::$2 in /home/catrope/php-5.4.0alpha3/testcase.php on line 13
NULL
Notice: Undefined property: stdClass::$2 in /home/catrope/php-5.4.0alpha3/testcase.php on line 14
NULL
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Nov 03 07:00:01 2025 UTC |
it's a known issue, there is only number key in array if it is ('looks like') a number.