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

Aro*_*eel 14 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

问题:在此对象上调用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));
Run Code Online (Sandbox Code Playgroud)

Ion*_*tan 23

这是一个已知的问题,可以在PHP6中解决.在那之前,使用isset()ArrayAccess::offsetExists().

  • 我不相信这是在手册的任何地方写的,因为它不是一个设计选择.这是一个设计疏忽,我可能会说一个错误.PHP语言中存在许多不一致之处.我已经在PHP内部邮件列表中提出了这个功能,人们同意我的观点,但是它将会很长时间才能实现.不幸的是,我不知道C. (4认同)
  • php 7.2.0alpha2的行为方式相同 (4认同)
  • 以下是该讨论的链接:http://marc.info/?l = php-internals&m = 122483924802616&w = 2 (2认同)
  • 感谢您的评论.潜水介绍SPL让我越来越意识到语言的不一致性.现在,我只是isset(). (2认同)
  • @cubsink似乎在PHP 5.4.24中按预期工作. (2认同)