$originalTags = $task->getTags();
$task->removeTag($tag1);
然后$tag1
也在$originalTags
删除。所以ArrayCollections的分配是通过引用完成的,我怎样才能将它克隆到一个新的ArrayCollection?
$originalTags = $task->getTags();
$task->removeTag($tag1);
然后$tag1
也在$originalTags
删除。所以ArrayCollections的分配是通过引用完成的,我怎样才能将它克隆到一个新的ArrayCollection?
您可以简单地使用本地PHP clone
为object cloning。
$originalTags = $task->getTags();
$task2 = clone $task;
$task2->removeTag($tag1);
我可能会在解决方案已经发现自己,但我不知道这是否会导致任何问题,因为我可能会丢失数据:
$originalTags = new ArrayCollection($task->getTags()->toArray());
而不是每次你需要getTags时间单独处理这个问题( ),从getTags而不是参考返回一个克隆。
public function getTags(){
return new ArrayCollection($this->tags->toArray());
}
,或者如果你需要保留通过引用传递getTags的功能,创建一个新的功能getClonedTags或变量传递给get函数将选择返回克隆的标签。
public function getTags($cloned = false){
if($cloned){
return new ArrayCollection($this->tags->toArray());
}
return clone $this->tags;
}
http://php.net/manual/en/language.oop5.cloning.php – DrKey
$任务是学说的实体吗? – JackalopeZero
@drkey很酷,很容易,你可以发表这个答案 – Asara