PHPのarray_key_exists()とSPL ArrayAccessインターフェイス:互換性がありませんか?

StackOverflow https://stackoverflow.com/questions/1538124

  •  20-09-2019
  •  | 
  •  

質問

私は、オブジェクトに私の配列を格納できるように、

私は、単純なコレクションクラスを書いてます:

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を呼び出すときには、この関数はSPLによって処理されていないようだと、それは常に「false」を返します。これを回避する方法はありますか?

をコンセプトの証明:

$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()を使用します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top