1
I know that the ArrayAccess exposes an access interface to 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 will 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 the database data was returned by an array and I wanted to implement this
ListObject, I could have trouble changing just the return (without having to change checks likein_arrayandarray_searchorarray_key_existsexisting in that system)?
Or you’d have to do more implementations - like 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]);
ArrayAccessonly "simulates" the interface of an array, but it does not return the expected results for the functions of thearraynative?
Finally, what are the limitations of an implement object of ArrayAccess in relation to the array native?
Friend,
$arr[[1, 2]]generates aIllegal offset typeso much forarrayas forArrayAccess. What did you mean ?– Wallace Maxters
@Wallacemaxters of course it generates... as I mentioned the implementation can not be direct! You need to implement the logic to get the offset of an array and not a variable as expected by Arrayaccess. The only way respecting the Arrayaccess interface is the way I put it. understand? I answered was the question.... What are the limitations!
– chambelix
@Wallacemaxters updated my answer to see if I can "illuminate" you for the problem I described... I hope I’ve helped!
– chambelix