Duplicate array but maintain pointer links

Posted by St. John Johnson on Stack Overflow See other posts from Stack Overflow or by St. John Johnson
Published on 2010-03-24T15:04:43Z Indexed on 2010/03/24 15:13 UTC
Read the original article Hit count: 137

Filed under:
|
|

Suppose I have an array 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?

© Stack Overflow or respective owner

Related posts about php

Related posts about arrays