Search code examples
phparraysphp4

Store Objects in Array difference in PHP 4 and 5


I had similar problem in the post here: Storing objects in an array with php

The test code is attached below.

The interesting thing is when I run the same code in PHP 4.3.9, and it outputs:

Array
(
    [0] => timitem Object
        (
            [t1] => a
            [t2] => a
        )

    [1] => timitem Object
        (
            [t1] => b
            [t2] => b
        )

    [2] => timitem Object
        (
            [t1] => c
            [t2] => c
        )

)

When I run it in PHP 5, and it outputs:

Array
(
    [0] => timItem Object
        (
            [t1] => c
            [t2] => c
        )

    [1] => timItem Object
        (
            [t1] => c
            [t2] => c
        )

    [2] => timItem Object
        (
            [t1] => c
            [t2] => c
        )

)

Can anyone point me a direction where I can find the related documentation regarding this changes in PHP 4 and 5?

Actually I am wondering if there is a switch I can turn off in PHP5 to do the same in PHP4. (I have a lot of this kind of code in an old project).

The test code is:

    <?php

class timItem{
  var $t1;
  var $t2;
  function timItem(){
  }
  function setItem($t1, $t2){
    $this->t1 = $t1;
    $this->t2 = $t2;
  }
} 

$arr = Array();

$item = new timItem();
$item->setItem("a","a");
$arr[] = $item;
$item->setItem("b","b");
$arr[] = $item;
$item->setItem("c","c");
$arr[] = $item;

print_r($arr);

?>

Solution

  • In PHP4, $arr[] = $item adds a copy of $item to $arr. In PHP5, a reference to $item is added to $arr.

    From PHP: Assignment Operators:

    Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. ...

    An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference in PHP 5.