PHP array_key_exists()和SPL ArrayAccess接口接口:不兼容?
题
我写了一个简单的集合类,这样我可以存储我的数组中的对象:
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()时,它总是,因为它似乎该功能不是由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));
解决方案
这是一个已知的问题,其可能可以在PHP6解决。在此之前,使用isset()
或ArrayAccess::offsetExists()
。
不隶属于 StackOverflow