Arrays, Objects, and Cloning

George Schlossnaglewrote a blog entry debating the "copy" vs. "handle" debate. While you can see my opinion on the whole matter in his blog someone else did ask whether or not Arrays are sopied or referenced with a handle by default, as well as whether the objects that may be indexed in the array are copied or just passed via a handle.

Well, as to the first question, arrays are copied as shown by this code:

which outputs:

That should be inferred as arrays are not objects in php, they are handled completely differently in almost every sence of the word.

The second question I wasn’t sure of so I wrote a little bit of code to see:

Which outputs:

So as you can see even though the arrays are cloned, objects within them are not. Reason for this is that any given variable holding an object in php does not technically hold an object. It holds a handle to that object (basically the original ID in my example.) The same thing is true for the ‘new’ construct. It also passes a handle, not an object. So, when an array is copied, php will just replicate each index’s value into the new array, when it comes accross an object it sees the handle, and copies it over (not the object itself).

Now, when you call ‘clone’ on an object, it does one of two things if there is a __clone() method defined for the object it will be called, if the method does not exist, then php creates a shallow copy of the object. Basically it copies each property from the original object to the new object. If a property contains a reference in the original object, the new object will contain that same reference.

This is all made MUCH clearer probably in PHP’s manual. However I thought I hadn’t added to much to my blog lately, so instead of making a horrendously long comment in someone else’s post I would just make a post of my own.

2 thoughts on “Arrays, Objects, and Cloning”

  1. “Array cloning” [i]still[/i] isn’t covered in the manual, and I didn’t expect reference members to also survive array cloning in PHP4, but they do. They also seem to survive any native array-to-array functions.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">