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.