1

So I want to store the ArrayCollection value, delete it and then reuse it in another entity. But it seems that the value is passed by reference so when its unset, the stored value is also unset.

$children = $role->getChildren();
var_dump(count($children)); // int(1)
$role->removeAllChildren();
var_dump(count($children)); // int(0)

/** **/

/**
 * @return Role
 */
public function removeAllChildren()
{
    foreach ($this->children as $child) {
        $this->removeChild($child);
    }

    return $this;
}


/**
 * @param Role $child
 *
 * @return Role
 */
public function removeChild(Role $child)
{
    if ($this->hasChild($child)) {
        $this->children->removeElement($child);

        // this calls unset($this->elements[$key]);
    }

    return $this;
}

So is there a way to store the arrayCollection value before I remove it ?

I'm on Symfony 3.4 by the way.

Chuck Norris
  • 1,125
  • 1
  • 12
  • 28
  • 1
    Depending on what you want to do with the collection, a `$children = clone $role->getChildren();` should work. (children must be clonable object) – j-guyon Mar 12 '18 at 10:03
  • Yeah, that work. I don't even know why I didn't try that. Thanks again. – Chuck Norris Mar 12 '18 at 10:05

1 Answers1

1

ArrayCollection is an object, you can use simple $chilrenCopy = clone $obj->getChildren(); on this object which will copy the object and assign to the new reference. There is also possibility to use design pattern for that called Memento

Robert
  • 19,800
  • 5
  • 55
  • 85