[nycphp-talk] Best way to copy array by value
Brian Dailey
support at dailytechnology.net
Mon Feb 26 10:16:59 EST 2007
If your professor was referring to PHP, it's possible he could have been
referring to objects, not arrays. Objects are copied by reference, so if
you do this:
$Item = new Item;
$Item2 = $Item;
$Item2->setProductId('12');
print $Item->getProductId();
Your output will be '12'. If you want to copy an object in PHP 5 you'll
need to use 'clone.'
Aaron Fischer wrote:
> Indeed it does. Sorry! I was led to believe (by my cs professor) that
> the default behavior when copying an array is that the copied array is
> not a new instance but is tied by pointers to the old array, so changes
> to one would change both of them. Other people in the class are using
> python and java, and apparently that is the case for them as they need
> to use separate functions to make sure the copy created is not tied to
> the old array.
>
> Down near the bottom of the php.net page on arrays, right before the
> user comments:
> You should be aware that array assignment always involves value copying.
> It also means that the internal array pointer used by current() and
> similar functions is reset. You need to use the reference operator to
> copy an array by reference.
> http://us2.php.net/manual/en/language.types.array.php
>
> -Aaron
>
> On Feb 25, 2007, at 5:39 PM, Daniel Convissor wrote:
>
>> Aaron:
>>
>> On Sun, Feb 25, 2007 at 03:47:45PM -0500, Aaron Fischer wrote:
>>> I need to copy an array by value, not by reference. Is there a best
>>> way to do this? Right now I found serialize/unserialize which seems
>>> to do the trick.
>>
>> What ARE you talking about? Copying by value is the default behavior in
>> PHP.
>>
>
> _______________________________________________
> New York PHP Community Talk Mailing List
> http://lists.nyphp.org/mailman/listinfo/talk
>
> NYPHPCon 2006 Presentations Online
> http://www.nyphpcon.com
>
> Show Your Participation in New York PHP
> http://www.nyphp.org/show_participation.php
>
>
More information about the talk
mailing list