2

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?

5
  • And by the way, if there is a better way to check whether my simple collection contains an element (without constructing a copy of array), it would be great to know. Commented Feb 11, 2018 at 9:20
  • plz provide the code for $this->getArrayCopy() Commented Feb 11, 2018 at 9:23
  • getArrayCopy is a method implemented in ArrayObject. It is not a custom method. Commented Feb 11, 2018 at 9:24
  • Have you enabled error reporting? Because when executing your code it throws an error at unset() for b (E_NOTICE : type 8 -- Undefined index: b) which means that you are not accessing the actual ArrayObject when trying to unset the b index. Commented Feb 11, 2018 at 9:27
  • @Tom Udding. I have not done that. But judging by the result this construct does not work. Commented Feb 11, 2018 at 9:29

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.