tags:

views:

231

answers:

1

I wrote a simple collection class so that I can store my arrays in objects:

class App_Collection implements ArrayAccess, IteratorAggregate, Countable
{
    public $data = array();

    public function count()
    {
     return count($this->data);
    }

    public function offsetExists($offset)
    {         
        return (isset($this->data[$offset]));
    }   

    public function offsetGet($offset)
    {  
        if ($this->offsetExists($offset))
     {
      return $this->data[$offset];
     }
     return false;
    }

    public function offsetSet($offset, $value)
    {         
        if ($offset)
     {
            $this->data[$offset] = $value;
     }  
        else
     {
            $this->data[] = $value; 
     }
    }

    public function offsetUnset($offset)
    {
        unset($this->data[$offset]);
    }

    public function getIterator()
    {
        return new ArrayIterator($this->data);
    }
}

Problem: when calling array_key_exists() on this object, it always returns "false" as it seems this function is not being handled by the SPL. Is there any way around this?

Proof of concept:

$collection = new App_Collection();
$collection['foo'] = 'bar';
// EXPECTED return value: bool(true) 
// REAL return value: bool(false) 
var_dump(array_key_exists('foo', $collection));
+3  A: 

This is a known issue which might be addressed in PHP6. Until then, use isset() or ArrayAccess::offsetExists().

Ionuț G. Stan
Thanks for the answer; could you provide a reference with that?
Aron Rotteveel
I don't believe this is written anywhere in the manual, because it wasn't a design choice. It was a design oversight, a bug I might say. There are many inconsistencies in the PHP language. I've proposed this functionality on the PHP internals mailing list, and people agreed with me, but it will going to be a long time until it will get implemented. I don't know C unfortunately.
Ionuț G. Stan
Ionuț G. Stan
Thanks for the comments. Diving intro SPL makes me realize more and more how inconsistent the language is. For now, I'll just isset().
Aron Rotteveel