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?
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?
You can simply use native PHP clone
for object cloning.
$originalTags = $task->getTags();
$task2 = clone $task;
$task2->removeTag($tag1);
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() );
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;
}