PHP array_key_exists()和SPL ArrayAccess接口:不兼容?

时间:2009-10-08 14:20:58

标签: php arrays spl

我编写了一个简单的集合类,以便将数组存储在对象中:

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);
    }
}

问题:在此对象上调用array_key_exists()时,它总是返回“false”,因为SPL似乎没有处理此函数。有没有办法解决这个问题?

概念证明:

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

1 个答案:

答案 0 :(得分:22)

这是一个已知的问题,可能在PHP6中解决。在此之前,请使用isset()ArrayAccess::offsetExists()