|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2010-04-28 15:30 UTC] david at grudl dot com
Description:
------------
Casting to (array) handles numeric keys wrong way:
Test script:
---------------
$obj = new stdClass;
$obj->{'10'} = 'as string';
$arr = (array) $obj;
$arr[10] = 'as integer';
var_dump($arr);
Expected result:
----------------
array(1) {
[10]=>
string(10) "as integer"
}
Actual result:
--------------
array(2) {
["10"]=>
string(9) "as string"
[10]=>
string(10) "as integer"
}
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Dec 17 02:00:01 2025 UTC |
I'd say there is no error in the way PHP handles this, as you are accessing $obj->{'10'} by a string key ( '10' === "10" => true ). $obj = new stdClass; $obj->{"10"} = 'as string'; $arr = (array) $obj; $arr["10"] = 'as string again'; var_dump($arr); would then produce something like array(1) { ["10"]=> string(10) "as string again" }Test 1: -------- class Test { protected $25twentyFive; } Expected result: Parse error. Actual result: Parse error. Test 2: -------- $obj = new stdClass; $obj->{25} = 'test assign as-integer'; $arr = (array) $obj; $arr[25] = 'test assign into array, with integer'; var_dump($arr); Expected result 2: ------------------- Parse error (since numeric variables are not compliant; when doing $obj->25 i get an parse error) Actual result 2: ----------------- array(2) { ["25"]=> string(22) "test assign as-integer" [25]=> string(36) "test assign into array, with integer" } Test 3: -------- $obj = new stdClass; $twentyFive = 25; $obj->$twentyFive = 'test assing with integer'; $arr = (array) $obj; $arr[$twentyFive] = 'test assign into array'; var_dump($arr); Expected result 3: ------------------- array(1) { [25]=> string(22) "test assign into array" } OR notice. Actual result 3: ----------------- array(2) { ["25"]=> string(24) "test assing with integer" [25]=> string(22) "test assign into array" } Proposed solution: ------------------- When doing: $twentyFive = 25; $obj->$twentyFive = 'some string'; php should raise a notice When doing: $obj->{25} = 'some string'; php should raise an error.