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 开发者_JS百科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);
?>
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.
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.
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.
精彩评论