php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #35663 Assigning object to new array item overwrites existing items
Submitted: 2005-12-13 22:53 UTC Modified: 2005-12-13 22:57 UTC
Votes:1
Avg. Score:1.0 ± 0.0
Reproduced:0 of 1 (0.0%)
From: jiri dot fogl at flyweb dot cz Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.1.1 OS: Linux, Windows
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: jiri dot fogl at flyweb dot cz
New email:
PHP Version: OS:

 

 [2005-12-13 22:53 UTC] jiri dot fogl at flyweb dot cz
Description:
------------
I wanted to have array of objects. After assigning an object variable to a new array item (using bracket syntax $array[] = $object;), all items are identical.
I found the bug in PHP 5.0.5/Linux and reproduced with 5.1.1/Windows. With 4.4.1 it works fine.
Direct assignment ($array[]->property = ...;) works.

Reproduce code:
---------------
<?php
  // This overwrites items:
  $array = Array();
  $object->property = 1;
  $array[] = $object;
  $object->property = 2;
  $array[] = $object;
  print_r($array);

/* This works:
 *  $array = Array();
 *  $array[]->property = 1;
 *  $array[]->property = 2;
 *  print_r($array);
 */
?>

Expected result:
----------------
After running this code I expect this output:
Array
(
    [0] => stdClass Object
        (
            [property] => 1
        )

    [1] => stdClass Object
        (
            [property] => 2
        )
)



Actual result:
--------------
Array
(
    [0] => stdClass Object
        (
            [property] => 2
        )

    [1] => stdClass Object
        (
            [property] => 2
        )
)



Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2005-12-13 22:57 UTC] tony2001@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

"When assigning an already created instance of an object to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A new instance of an already created object can be made by cloning it."
http://www.php.net/manual/en/language.oop5.basic.php
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Jul 16 18:01:31 2025 UTC