2017-04-07 79 views
0

当我做克隆主义的ArrayCollection没有参考

$originalTags = $task->getTags(); 
$task->removeTag($tag1); 

然后$tag1也在$originalTags删除。所以ArrayCollections的分配是通过引用完成的,我怎样才能将它克隆到一个新的ArrayCollection?

+0

http://php.net/manual/en/language.oop5.cloning.php – DrKey

+0

$任务是学说的实体吗? – JackalopeZero

+1

@drkey很酷,很容易,你可以发表这个答案 – Asara

回答

0

您可以简单地使用本地PHP cloneobject cloning

$originalTags = $task->getTags(); 
$task2 = clone $task; 
$task2->removeTag($tag1); 
0

我可能会在解决方案已经发现自己,但我不知道这是否会导致任何问题,因为我可能会丢失数据:

$originalTags = new ArrayCollection($task->getTags()->toArray()); 
0

而不是每次你需要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; 
}