I am having a problem with using an object as a prototype for some other objects.
The below code is expected to persist all instances of the object Container (visible in this code below is $module1 and $module2), however only the last one is persisted, and I assume it is due to the way I copy a prototype object.
Should I copy the prototype in some other way?
//Create module prototype
$module = new Container();
$module->setCompany($currentCompany);
$module->setContainerType($typeModule);
$module->setParent($entity);
//Set the modules in use by this template (structure a bit ugly here, but makes it easier when dealing with the layout on other areas of the app)
if ($size = $template->getModule1()) {
$module1 = $module; //copy the prototype
$module1->setName('Module1'); //Give a unique name
$module1->setContainerSize($size); //Copy the size from the layoutTemplate
$em->persist($module1); //Persist this module
$layout->setModule1($module1); //Connect this container to become a module in the layout
}
if ($size = $template->getModule2()) {
$module2 = $module; //copy the prototype
$module2->setName('Module2'); //Give a unique name
$module2->setContainerSize($size); //Copy the size from the layoutTemplate
$em->persist($module2); //Persist this module
$layout->setModule2($module2); //Connect this container to become a module in the layout
}
You don’t really copy the object, you only create a new variable alias to the same object (they use the same underlying object). This would work with arrays, but not with objects.
You can use
cloneto create a (shallow) copy of an object:Keep in mind though that $module and $module1 will have the same objects referenced. I,e if ContainerType is an object, the $module and $module1 will reference the same instance of ContainerType, which may or may not be what you want.
You can read more about cloning in PHP5 here