开发者

Duplicate array but maintain pointer links

开发者 https://www.devze.com 2022-12-25 00:46 出处:网络
Suppose I have an arr开发者_运维百科ay of nodes (objects).I need to create a duplicate of this array that I can modify without affecting the source array.But changing the nodes will affect the source

Suppose I have an arr开发者_运维百科ay of nodes (objects). I need to create a duplicate of this array that I can modify without affecting the source array. But changing the nodes will affect the source nodes. Basically maintaining pointers to the objects instead of duplicating their values.

// node(x, y)
$array[0] = new node(15, 10);
$array[1] = new node(30, -10);
$array[2] = new node(-2, 49);

// Some sort of copy system
$array2 = $array;

// Just to show modification to the array doesn't affect the source array
array_pop($array2);
if (count($array) == count($array2))
  echo "Fail";    

// Changing the node value should affect the source array
$array2[0]->x = 30;
if ($array2[0]->x == $array[0]->x)
   echo "Goal";

What would be the best way to do this?


If you use PHP 5:

Have you run your code? It is already working, no need to change anything. I get:

Goal

when I run it.

Most likely this is because the values of $array are already references.

Read also this question. Although he OP wanted to achieve the opposite, it could be helpful to understand how array copying works in PHP.

Update:

This behaviour, when copying arrays with objects, the reference to the object is copied instead the object itself, was reported as a bug. But no new information on this yet.


If you use PHP 4:

(Why do you still use it?)

You have to do something like:

$array2 = array();

for($i = 0; $i<count($array); $i++) {
    $array2[$i] = &$array[$i];
}


it is some time that I don' write PHP code, but does the code

// Some sort of copy system
$array2 = $array;

actually work?

Don't you have to copy each element of the array in a new one?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号