array_key_exists PHP () y SPL ArrayAccess interfaz: no es compatible?
Pregunta
Me escribió una clase de colección sencilla para que pueda guardar mis matrices de objetos:
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);
}
}
Problema: al llamar array_key_exists () en este objeto, siempre devuelve "falso", ya que parece que esta función no está siendo manejado por el SPL. ¿Hay alguna forma de evitar esto?
Prueba de concepto:
$collection = new App_Collection();
$collection['foo'] = 'bar';
// EXPECTED return value: bool(true)
// REAL return value: bool(false)
var_dump(array_key_exists('foo', $collection));
Solución
Este es un problema conocido que podría se abordará en PHP6. Hasta entonces, utilizar isset()
o ArrayAccess::offsetExists()
.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow