Array Items By Value¶
<?php
class X {
public int $i;
}
$array = [new x, new x, new x];
$array[0]->i = 0;
$array[1]->i = 1;
$array[2]->i = 2;
function foo(array $array) {
$array[] = new x;
$array[2]->i = 12;
$array[3]->i = 3;
print count($array)." elements in foo
";
}
print count($array)." elements before foo
";
foo($array);
print count($array)." elements after foo
";
print_r($array[2]);
In this code, an array is built with objects. The array is passed by value to the function. The function updates both the array and one of the elements. When the function is finished, the array in the calling context is still the same, but the object #2 has changed.
In this case, PHP applies copy on write, or COW: the array is passed by value, and duplicated only when it is updated. But the copy applies to the objects, which are always passed by reference!
Here, the elements in the array are references, and their update is applied to the original object, in the calling context.
This is a similar situation than with readonly properties, and array_fill(): the reference to the object is unchanged, but the object itself may be updated.
In general, objects may be considered as global values.
This also applies to array_pad().
Since PHP 8.5, it is possible to use array_map(clone(...), $array) on the array to make all the objects distinct, since clone() is now a function.
See Also¶
Passing array of object by value [Try me]
PHP Features¶
Last updated: 14 July 2026