2

When I do

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

then $tag1 is also removed in $originalTags. So the assignment of ArrayCollections is made by reference, how can I clone it to a new ArrayCollection?

Asara
  • 2,791
  • 3
  • 26
  • 55

3 Answers3

3

You can simply use native PHP clone for object cloning.

$originalTags = $task->getTags();
$task2 = clone $task;
$task2->removeTag($tag1);
DrKey
  • 3,365
  • 2
  • 29
  • 46
0

I might have found the solution myself, but I don't know if this may result in any problems because I could lose data:

$originalTags = new ArrayCollection( $task->getTags()->toArray() );
Asara
  • 2,791
  • 3
  • 26
  • 55
0

Rather than handling this problem individually every time you need getTags(), return a clone from getTags rather than the reference.

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

or if you need to preserve the functionality of getTags passing by reference, create a new function getClonedTags or pass a variable to the get function which will optionally return cloned tags.

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

    return clone $this->tags;
}
RonnyKnoxville
  • 6,166
  • 10
  • 46
  • 75