what is the purpose of ArrayAccess interface in php?

Viewed 100

ArrayAccess Interface is

used to provide accessing objects as arrays.

as the documentation says. but most of array function not working on it. Also the normal object function have problems with this conversion. so what is the idea. so for example

  1. You can't call 'array_key_exists' on an object of class which implements this interface.
  2. class can't be iterable unless the new class implements Iterator interface as well.
  3. You can't assign by reference with the ArrayAccess.(you have to make your own implementation(a custom function to do this).
  4. Most of functions for arrays Not working on classes implement this interface.

so why we put ourselves in pain if there is no clear reason.

1 Answers

The idea is to allow you to access the properties of an object using array syntax. This can often be very convenient, and many utility classes implement it. For instance, Eloquent models in Laravel implement it, as do collections.

It doesn't mean an object that implements that interface can be passed as an argument to one of the array functions. However, it may often make sense to implement similar methods on an object if the data it stores is an array - for instance, Laravel collections implement methods like map() and filter(), and these may use their array counterparts internally. Using these methods often makes for much cleaner, easier to understand code because you can chain each step. Languages like JavaScript and Python where arrays are objects that have these sorts of methods out of the box are historically better at functional programming and using something like Laravel collections instead of arrays enables this style of programming in PHP too. I highly recommend the book Refactoring to Collections by Adam Wathan for more details.

It's also useful when examining an object in a REPL like PsySh as you can more easily access individual properties. Implementing Traversable as well means you can iterate over data when examining it . You can also typehint the interface so a method can accept anything that implements it

Related