|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2004-06-23 13:56 UTC] bf at mediaspace dot net
Description:
------------
If using "new" in a for-loop it seems that the same instance is re-used all the time. This is not what is expected, because in terms of OOP the new-operator schould create a new instance every time.
Tested with 4.3.3 and 5.0RC3
Reproduce code:
---------------
<?
class Test {
var $iterator;
}
$a=array();
for($i=0;$i<10;$i++) {
$object = new Test();
$object->iterator=$i;
$a[]=&$object;
}
foreach($a as $object) {
echo $object->iterator."<br>";
}
?>
Expected result:
----------------
Output should be:
0
1
2
3
4
5
6
7
8
9
Actual result:
--------------
Output actual is:
9
9
9
9
9
9
9
9
9
9
-> The same instance is reused all the time.
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Fri Oct 24 20:00:01 2025 UTC |
When you assign $a[] &= $object; not only is $a[$i] a reference to $object, but it also works the other way around. So in your next iteration, when you call $object = new Test(); you ARE creating a new object, unfortuately this new object is overwriting $object, which means it's also overwriting $a[$i-1]. Since the original instance is no longer referenced, it gets destroyed and you're left with one object. To get your expected behavior put unset($object); after your assign it to your array: for($i=0;$i<10;$i++) { $object = new Test(); $object->iterator=$i; $a[]=&$object; unset($object); } This will de-couple the reference link between $object and $a[$i].