【问题标题】:PHP array_key_exists() and SPL ArrayAccess interface: not compatible?PHP array_key_exists() 和 SPL ArrayAccess 接口:不兼容?
【发布时间】: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

标签: php arrays spl


【解决方案1】:

这是一个已知问题,可能在 PHP6 中得到解决。在此之前,请使用isset()ArrayAccess::offsetExists()

【讨论】:

  • 我不相信这会写在手册的任何地方,因为它不是设计选择。这是一个设计疏忽,我可能会说这是一个错误。 PHP 语言有许多不一致之处。我已经在 PHP 内部邮件列表中提出了这个功能,人们同意我的看法,但是要实现它还需要很长时间。不幸的是,我不知道 C。
  • 感谢 cmets。 Diving intro SPL 让我越来越意识到这种语言是多么的不一致。现在,我只需要 isset()。
  • @cubsink 在 PHP 5.4.24 中似乎可以正常工作。
  • php 7.2.0alpha2 的行为方式相同
猜你喜欢
  • 2012-07-05
  • 1970-01-01
  • 2012-07-06
  • 1970-01-01
  • 2011-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多