11
我寫了一個簡單的集合類,這樣我可以存儲我的數組中的對象: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()的時候,它總是因爲它似乎返回「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));
感謝您的回答;你能提供一個參考嗎? – 2009-10-08 14:25:15
我不認爲這是寫在手冊的任何地方,因爲它不是一個設計選擇。這是一個設計監督,我可能會說一個錯誤。 PHP語言中有很多不一致的地方。我已經在PHP內部郵件列表中提出了這個功能,並且人們同意我的觀點,但是它將會很長時間纔會實現。不幸的是我不知道C. – 2009-10-08 14:29:37
以下是該討論的鏈接:http://marc.info/?l=php-internals&m=122483924802616&w=2 – 2009-10-08 14:32:22