加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 16:34:01 所属栏目:PHP教程 来源:网络整理
导读:我写了一个简单的集合类,以便我可以将数组存储在对象中: class App_Collection implements ArrayAccess,IteratorAggregate,Countable{ public $data = array(); public function count() { return count($this-data); } public function offsetExists($offs
我写了一个简单的集合类,以便我可以将数组存储在对象中:
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));
这是PHP6中可以解决的已知问题.在此之前,使用isset()或ArrayAccess :: offsetExists().

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读