Php 一个原型对象的多个实例,只有最后一个得到持久化

Php 一个原型对象的多个实例,只有最后一个得到持久化,php,symfony,doctrine,Php,Symfony,Doctrine,我在使用对象作为其他对象的原型时遇到问题 下面的代码将持久化对象容器的所有实例(在下面的代码中可见的是$module1和$module2),但是只有最后一个实例被持久化,我假设这是由于我复制原型对象的方式 我应该以其他方式复制原型吗 //Create module prototype $module = new Container(); $module->setCompany($currentCompany); $module->set

我在使用对象作为其他对象的原型时遇到问题

下面的代码将持久化对象容器的所有实例(在下面的代码中可见的是$module1和$module2),但是只有最后一个实例被持久化,我假设这是由于我复制原型对象的方式

我应该以其他方式复制原型吗

//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
        }

您并没有真正复制对象,只是为同一对象创建了一个新的变量别名(它们使用相同的基础对象)。这适用于数组,但不适用于对象

您可以使用
clone
创建对象的(浅层)副本:

$module1 = clone $module;
请记住,$module和$module1将引用相同的对象。一、 e如果ContainerType是一个对象,$module和$module1将引用ContainerType的同一个实例,这可能是您想要的,也可能不是您想要的


你可以

我不能100%确定这一点,因为我没有使用此框架的任何经验

但是在if语句中,缺少一个等号来比较这些值

if ($size = $template->getModule1()) {
应该是

if ($size == $template->getModule1()) {

您拥有的if将始终为true,并且值将在第二个if语句中被覆盖。试着按照建议更改这两行,看看这是否解决了问题。

正是我所怀疑的,你给了我我所需要的,非常感谢!哦,不,这是有意的,我使用$size变量几行,而不必从条件=)重复该函数调用。)