I know that ArrayAccess
exposes an interface to access some elements of the object as if it were a array
Example:
class ListObject implements ArrayAccess{
protected $storage;
public function offsetSet($key, $value)
{
$this->storage[$key] = $value;
}
public function &offsetGet($key)
{
return $this->storage[$key];
}
public function offsetUnset($key)
{
unset($this->storage[$key]);
}
public function offsetExists($key)
{
return array_key_exists($key, $this->storage);
}
}
$list = new ListObject;
$list[1] = 'Primeiro';
$list[2] = 'Segundo';
However, when I test the existence of some elements, this is the return:
var_dump(array_key_exists(2, $list)); // retorna false e não gera erros :\
var_dump(isset($list[2])); // true
And in some other functions there were also errors when trying to use the object that implements ArrayAccess
.
- If I were on a system where database data was returned by an array and I wanted to implement this
ListObject
, I might have trouble changing only the return (without having to change checks likein_array
andarray_search
orarray_key_exists
in that system)?
Or would you have to do more implementations - such as Countable
, IteratorAggregate
, and the like?
Example:
DB::table('tabela')->get();
// array(0 => array('id' => 1, 'nome' => 2))
DB::table('tabela')->get();
// ListObject(['id' => 1, 'nome' => 2]);
-
ArrayAccess
only "simulates" the interface of an array, but does it not return the expected results for the functions of thearray
native?
Finally, what are the limitations of an implementor object of ArrayAccess
relative to array
native?