|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2006-04-21 13:33 UTC] sirber at webernic dot com
Description:
------------
When you foreach an array of object, if you modify the object, the source is modified.
PHP4: work as expected
PHP5 with compatibility on: work as expected
PHP5: source gets modified
Reproduce code:
---------------
$aTmp = array();
$oTmp = new stdClass();
$oTmp->id = 1;
$aTmp[] = $oTmp;
$oTmp = new stdClass();
$oTmp->id = 2;
$aTmp[] = $oTmp;
$oTmp = new stdClass();
$oTmp->id = 3;
$aTmp[] = $oTmp;
$oTmp = new stdClass();
$oTmp->id = 4;
$aTmp[] = $oTmp;
foreach ($aTmp as $iKey => $oTest)
$oTest->id = 'tea';
var_dump($aTmp);
Expected result:
----------------
array(4) {
[0]=>
object(stdClass)#1 (1) {
["id"]=>
int(1)
}
[1]=>
object(stdClass)#2 (1) {
["id"]=>
int(2)
}
[2]=>
object(stdClass)#3 (1) {
["id"]=>
int(3)
}
[3]=>
object(stdClass)#4 (1) {
["id"]=>
int(4)
}
}
Actual result:
--------------
array(4) {
[0]=>
object(stdClass)#1 (1) {
["id"]=>
string(3) "tea"
}
[1]=>
object(stdClass)#2 (1) {
["id"]=>
string(3) "tea"
}
[2]=>
object(stdClass)#3 (1) {
["id"]=>
string(3) "tea"
}
[3]=>
object(stdClass)#4 (1) {
["id"]=>
string(3) "tea"
}
}
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Fri Dec 05 13:00:02 2025 UTC |
Same result with a copy of the array. Source array and the copy are modified. Reproduce code: --------------- $aTmp = array(); $oTmp = new stdClass(); $oTmp->id = 1; $aTmp[] = $oTmp; $oTmp = new stdClass(); $oTmp->id = 2; $aTmp3 = $aTmp foreach ($aTmp3 as $iKey => $oTest) $oTest->id = 'tea'; var_dump($aTmp, $aTmp3); Expected result: ---------------- array(2) { [0]=> object(stdClass)#1 (1) { ["id"]=> int(1) } [1]=> object(stdClass)#2 (1) { ["id"]=> int(2) } } array(2) { [0]=> object(stdClass)#1 (1) { ["id"]=> int(1) } [1]=> object(stdClass)#2 (1) { ["id"]=> int(2) } } Actual result: -------------- array(2) { [0]=> object(stdClass)#1 (1) { ["id"]=> string(3) "tea" } [1]=> object(stdClass)#2 (1) { ["id"]=> string(3) "tea" } } array(2) { [0]=> object(stdClass)#1 (1) { ["id"]=> string(3) "tea" } [1]=> object(stdClass)#2 (1) { ["id"]=> string(3) "tea" } }