Any reason PHP doesn't iterate over an array by reference?

$arr = array(array(array())); foreach($arr as $subarr) { $subarr[] = 1; } var_dump($arr); 

Conclusion:

 array(1) { [0]=> array(1) { [0]=> array(0) { } } } 

But for the object, the link is:

 class testclass { } $arr = array(new testclass()); foreach($arr as $subarr) { $subarr->new = 1; } var_dump($arr); 

Conclusion:

 array(1) { [0]=> object(testclass)#1 (1) { ["new"]=> int(1) } } 

Why treat array from object ?

+4
source share
3 answers

PHP passes all objects by reference. (PHP5?)

PHP passes all arrays by value.

Initially, PHP passed both objects and arrays by value, but in order to reduce the number of created objects, they switch objects to automatically pass by reference.

There is actually no logical reason why PHP does not pass arrays by reference, but that is how the language works. If you need to, you can iterate over arrays by value, but you must explicitly declare the value by reference:

 foreach ( $myArray as &$val ){ $val = 1; //updates the element in $myArray } 

Thanks to Yacoby for an example.

Frankly, I prefer arrays to be passed by value, because arrays are a type of basic data structure, and objects are more complex data structures. The current system makes sense, at least for me.

+14
source

Why should the array and object be handled the same?

PHP simply passes objects by reference (->) and passes all arrays by value.

If all objects were passed by value, the script will make many copies of the same class, thereby using more memory.

+1
source

Foreach copies an iterated array because it allows you to modify the original array inside Foreach , and is easier to use in this way. Is not it, your first example will explode. It is not possible to save PHP to copy an array inside Foreach . Even with the pass-item-by-reference foreach($foo as &$bar) syntax, you will still work on a copy of the array that contains the links instead of the actual values.

On the other hand, objects are expected from most object-oriented developers, which are always passed by reference. This happened in PHP 5. And when you copy an array containing objects, you actually copy references to objects; therefore, even if you are working on a copy of the array, you are working on the same objects.

If you want to copy an object, use the clone operator. As far as I know, there is no way that certain objects are always passed by value.

 $foo = new Foo; $bar = clone $foo; 
+1
source

Source: https://habr.com/ru/post/1303412/


All Articles