php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #28893 Unexpected behaviour of "new"
Submitted: 2004-06-23 13:56 UTC Modified: 2004-06-24 02:07 UTC
From: bf at mediaspace dot net Assigned:
Status: Not a bug Package: Class/Object related
PHP Version: 5.0.0RC3 OS: Linux
Private report: No CVE-ID: None
 [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.

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2004-06-23 18:48 UTC] rodolfo at rodsoft dot org
I've experienced something similar with 'clone' when the cloned variable is used in mysqli_bind_result, as I said in bug #28870.
 [2004-06-23 18:50 UTC] rodolfo at rodsoft dot org
I've just ran your example and found that if you write a[]=$object (without &), it runs flawlessly.
 [2004-06-24 01:30 UTC] bla at discardmail dot com
i must agree rodolfo, this is correct for php5
but in php4 it is buggy
 [2004-06-24 02:06 UTC] pollita@php.net
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].
 [2004-06-24 02:07 UTC] pollita@php.net
.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri May 03 19:01:32 2024 UTC