2

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);

?>

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That explained everything. Thanks.
2

Because PHP5 is said to be object oriented, you should change your assignments into something like this:

$arr[] = clone $item.

I don't think, that you can force PHP5 to act in a non-object-oriented way.

Comments

1

The difference is not in the arrays as such, but in the way PHP handles objects. PHP 4 would pretty much always make a copy of an item when you assigned a variable, but PHP 5 works more like Java, C# etc where assignment makes a reference.

Have a look at http://au.php.net/manual/en/language.oop5.references.php for more info.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.