如何将一个对象的所有值克隆到另一个对象上

如何将一个对象的所有值克隆到另一个对象上

本文介绍了教义 2:如何将一个对象的所有值克隆到另一个对象上(ID 除外)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 $entity 变量中,有一个与 $other_address 类型相同的对象,但填充了所有字段值.

In $entity variable, there is an object of same type as $other_address, but with all field values filled in.

我想将 $other_address 对象中的所有字段设置为与 $entity 对象具有完全相同的值.

I want to set all fields in $other_address object to have exact same values as $entity object.

这在少于 N 行的情况下是否可行,其中 N 是我需要设置的字段数?

Is this doable in less then N number of lines, where N is number of fields I need to set?

我试过clone"关键字,但没有用.

I tried "clone" keyword, but it didnt work.

这是代码.

                $other_address = $em->getRepository('PennyHomeBundle:Address')
          ->findBy(array('user' => $this->get('security.context')->getToken()->getUser()->getId(), 'type' => $check_type));
                $other_address = $other_address[0];


                //I want to set all values in this object to have values from another object of same type
                $other_address->setName($entity->getName());
                $other_address->setAddress1($entity->getAddress1());
                $other_address->setAddress2($entity->getAddress2());
                $other_address->setSuburbTown($entity->getSuburbTown());
                $other_address->setCityState($entity->getCityState());
                $other_address->setPostZipCode($entity->getPostZipCode());
                $other_address->setPhone($entity->getPhone());
                $other_address->setType($check_type);

推荐答案

我不知道为什么克隆不起作用.

I'm not sure why cloning won't work.

这似乎对我有用,至少在基本测试用例中:

This seems to work for me, at least in a basic test case:

$A = $em->find('SomeEntity',1);

$B = clone $A;
$B->setId(null);

如果您需要担心人际关系,您可能需要安全地实现 __clone 以便它对相关实体执行您希望它执行的操作.

If you've got relationships to worry about, you might want to safely implement __clone so it does what you want it to do with related entities.

这篇关于教义 2:如何将一个对象的所有值克隆到另一个对象上(ID 除外)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 08:05