I'm building an array of objects. I need this array to only contain once instance of a given object, having multiple references to the same object should throw an exception. I'm using the following code to achieve this:
public function addField ($name, iface\Node $field)
{
// Prevent the same field being added multiple times
if (!in_array ($field, $this -> fields))
{
$this -> fields [$name] = $field;
$field -> setParent ($this);
}
else
{
throw new \InvalidArgumentException ('This field cannot be added to this group');
}
return ($this);
}
This started leading to problems when I started implementing the objects that implement the Node interface, as they can include circular references (they hold a collection of their child nodes, with each child holding a reference to its parent). Trying to add a field can result in the following error being generated:
PHP Fatal error: Nesting level too deep - recursive dependency?
I suspect that PHP is trying to traverse the entire object array, rather than just comparing the object references to see if they hold the same value and therefore point to the same object.
What I need in_array to do is just compare the object references it stores with the object reference of field. This would prevent it trying to traverse the whole object tree and running into the recursion problem.
Is there a way of doing this?