【发布时间】:2010-12-05 00:27:20
【问题描述】:
我编写了一个简单的集合类,以便可以将我的数组存储在对象中:
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));
【问题讨论】:
-
array_key_exists 不适用于 ArrayAccess 但它可以使用 ArrayObject,请参阅:3v4l.org/gYeCM