Here is my best practice on an array of objects and cloning. Usually it is a good idea, to have a Collection class for each class of objects (or interface), which are used in an array. With the magic function __clone
cloning becomes a formalized routine:
class Collection extends ArrayObject
{
public function __clone()
{
foreach ($this as $key => $property) {
$this[$key] = clone $property;
}
}
}
To clone your array, use it as Collection and then clone it:
$arrayObject = new Collection($myArray);
$clonedArrayObject = clone $arrayObject;
One step further, you should add a clone method to your class and each sub-class, too. This is important for deep cloning, or you might have unintended side effects:
class MyClass
{
public function __clone()
{
$this->propertyContainingObject = clone $this->propertyContainingObject;
}
}
An important note on using ArrayObject is, that you cannot use is_array()
any longer. So be aware of this on refactoring your code.