没有引用的克隆学说 ArrayCollection

clone doctrine ArrayCollection without reference

当我做的时候

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

然后$tag1也在$originalTags中被删除。所以 ArrayCollections 的赋值是通过引用进行的,我如何将它克隆到一个新的 ArrayCollection?

我可能自己找到了解决方案,但我不知道这是否会导致任何问题,因为我可能会丢失数据:

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

与其在每次需要 getTags() 时单独处理这个问题,return getTags 的克隆而不是引用。

public function getTags(){
     return new ArrayCollection($this->tags->toArray());
}

或者如果您需要保留通过引用传递 getTags 的功能,请创建一个新函数 getClonedTags 或将变量传递给 get 函数,该函数可以选择 return 克隆标签。

public function getTags($cloned = false){
    if($cloned){
        return new ArrayCollection($this->tags->toArray());
    }

    return clone $this->tags;
}

您可以简单地使用本机 PHP clone 作为 object cloning

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