Jacobian
Jacobian

Reputation: 10802

Unable to remove element from ArrayObject

I have a simple class which extends ArrayObject. It looks like so:

class SimpleCollection extends ArrayObject
{

    public function __construct($arr = [])
    {
        parent::__construct($arr, ArrayObject::ARRAY_AS_PROPS);   
    }


    public function contains($value)   
    {
        return in_array($value, $this->getArrayCopy());        
    }


    public function remove($vertex)
    {
        unset($this[$vertex]);     
    }
}

Its constructor and contains method work as expected. But remove method does not work:

$arr = new SimpleCollection(['b']);

$arr->remove('b');

echo $arr->contains('b'); 

The last command prints true, even though I tried to remove an element form my object. What is wrong with that and how can I fix it?

Upvotes: 2

Views: 62

Answers (1)

Tom Udding
Tom Udding

Reputation: 2294

As I mentioned in my comment it throws an error at the unset() function because index b is not defined. If we take a look at var_dump($arr) this makes sense:

object(SimpleCollection)#1 (1) { 
    ["storage":"ArrayObject":private] => array(1) {
        [0]=> string(1) "b" 
    }
}

When you do $arr = new SimpleCollection(['b']); it doesn't make b the index, it makes b the value with an index of 0.

Which also makes sense because ['b'] is

array(1) { 
    [0]=> string(1) "b"
} 

To get the desired result you'll have to change ['b'] to something like ['b' => 'something']. Then the remove() function will work.

Upvotes: 2

Related Questions