views:

2005

answers:

5

I have the following code:

$data['x'] = $this->x->getResults();  

$data['y'] = $data['x'];

//some code here to modify $data['y']
//this causes (undesirably) $data['x] to be modified as well

I guess since all the elements of $data are themselves references, modifying $data['y'] also modifies $data['x']..which is NOT what I want. I want $data['x'] to remain the same. Is there any way to dereference the elements here so that I can copy the elements by value?

Thanks.

Update: $this->x->getResults(); returns an object array. So I can then do something like: $data['x'][0]->date_create ...

Update: my latest attempt to clone the array looks something like this:

   $data['x'] = $this->x->getResults();     
   $data['y'] = $data['y'];
   foreach($data['x'] as $key=>$row) {
       $data['y'][$key]->some_attr = clone $row->some_attr;
   }

Am I way off here? I keep getting a "__clone method called on non-object" error. From reading the responses it seems like my best option is to iterate over each element and clone it (which is what I was trying to do with that code..).

UPDATE: Just solved it!: inside the foreach loop I just needed to change the line to:

$data['y'][$key] = clone $row;

And it works! Thanks to everyone for the help.

+3  A: 

Not simple. Read about clone

BUT! if your elements are not objects and not refence type variables you have no problem.

Example for reference types:

$v=11;
$arr[]=&$v;
Itay Moav
why is it that I only have a problem if the elements are objects? is it because objects are themselves references?
es11
In PHP, (as of version 5 IICRC) all objects are passed by reference by default.
Mike B
This answer is not quite true. It should read "If your elements are not references, you have no problem.". You can have references that are not objects.
zombat
Thanx, edited the answer accordingly
Itay Moav
+1  A: 

Hi,

If you are working with objects, you might want to take a look at clone, to create a copy of an object, instead of a reference.

Here is a very short example :

First, with an array, it works by value :

$data['x'] = array(
    'a' => 'test',
    'b' => 'glop',
);
$data['y'] = $data['x'];
$data['y'][0] = 'Hello, world!';
var_dump($data['x']); // a => test : no problem with arrays

By default, with objects, it works by reference :

$data['x'] = (object)array(
    'a' => 'test',
    'b' => 'glop',
);
$data['y'] = $data['x'];
$data['y']->a = 'Hello, world!';
var_dump($data['x']); // a => Hello, world! : objects are by ref

But, if you clone the object, you work on a copy :
I guess this is your case ?

$data['x'] = (object)array(
    'a' => 'test',
    'b' => 'glop',
);
$data['y'] = clone $data['x'];
$data['y']->a = 'Hello, world!';
var_dump($data['x']); // a => test : no ref, because of cloning

Hope this helps,

Pascal MARTIN
thanks for the code sample..do you know if the clone function is relatively efficient? I ask because I know that in java it is usually best to avoid this if possible.
es11
I have no idea about the efficiency, but if you need the functionnality, it doesn't really matter, does it ? (and, considering you are doing a DB query just a while before, it shouldn't be that long, in comparison with the rest of the script :-) )
Pascal MARTIN
...good point :)
es11
+3  A: 

You can take advantage of the fact that PHP will dereference the results of a function call.

Here's some example code I whipped up:

$x = 'x';
$y = 'y';
$arr = array(&$x,&$y);
print_r($arr);

echo "<br/>";
$arr2 = $arr;
$arr2[0] = 'zzz';
print_r($arr);
print_r($arr2);

echo "<br/>";
$arr2 = array_flip(array_flip($arr));
$arr2[0] = '123';
print_r($arr);
print_r($arr2);

The results look like this:

Array ( [0] => x [1] => y )
Array ( [0] => zzz [1] => y ) Array ( [0] => zzz [1] => y )
Array ( [0] => zzz [1] => y ) Array ( [0] => 123 [1] => y ) 

You can see that the results of using array_flip() during the assigment of $arr to $arr2 results in differences in the subsequent changes to $arr2, as the array_flip() calls forces a dereference.

It doesn't seem terribly efficient, but it might work for you if $this->x->getResults() is returning an array:

$data['x'] = array_flip(array_flip($this->x->getResults()));
$data['y'] = $data['x'];

See this (unanswered) thread for another example.

If everything in your returned array is an object however, then the only way to copy an object is to use clone(), and you would have to iterate through $data['x'] and clone each element into $data['y'].

Example:

$data['x'] = $this->x->getResults();
$data['y'] = array();
foreach($data['x'] as $key => $obj) {
    $data['y'][$key] = clone $obj;
}
zombat
I am having some trouble with this: like you mentioned in your last sentence, everything in my returned array is an object..could you maybe post some code showing how to iterate over the array and clone each element? I keep getting a "_clone method called on non-object" error. Thanks.
es11
nice you beat me to it! thanks for your help!
es11
No problem, I added an example. `clone` only works on actual objects, so if the return result of `$this->x->getResults();` is an array of objects instead of an object, then you can't clone the array, you have to clone each element of the array separately.
zombat
A: 

All of this is great but; What if I have an object that has references to different other objects and even a few collections [arrays] of some even other objects; and I want to make a copy of that instance ?? Must I clone the entire instance structure and performing a clone on every other referenced object and the collections ?? If yes ... What a shit !!!

The _clone call should be aware of the other referenced objects inside an object, and do the clone as well. After all, why am I doing a clone, don't you think ??

1ukaz
A: 

bnuhuhhjnnnghjkkkkkkkkkkkkkkkkkkkkkkkkkkkkhjkjkjkjkhhhhhhhhhhhhhhhhhhhhhhhhhsksksksksksksksksklaaaaaaaaaahfkjkfjdfijidjiiidjfdijijdijifjdifjjiijd<IOAjsdja8ijfiiSfujsdf>FIehfushsvhhjsdgvsduyh<dhvjshduudfisfeifuwiufwfidif>sdjgdgjksdgjiwegngjnjvbnvlaifwiegugugnvnsjkdvas

lakdhafhj hfuwshfeufw jnjweufiw

lakdhafhj hfuwshfeufw