5

Implementing ArrayAccess Interface in PHP , We can access Object Properties as Array Keys . What are the benefits of having an Object behave like an Array?

Like I see Frameworks implementing 'FORM' with ArrayAccess Interface and then we can access (HTML) Form Objects Fields something like,

$form['nameField']   instead-of  $form->nameField 
$form['titleField']  instead-of  $form->titleField

Whats the benefit of using $form['nameField] instead-of $form->nameField

Is it Speed of 'Array Data Structures' or portability between Object and Array Forms ?

Or Am I missing something? :)

hakre
  • 193,403
  • 52
  • 435
  • 836
Rohit Chauhan
  • 631
  • 7
  • 17
  • Possible duplicate: http://stackoverflow.com/questions/4072927/what-are-the-benefits-of-using-spl-arrayobject-arrayiterator-recursivearrayiter – Rob Olmos Nov 30 '10 at 23:04
  • As I read in a book, ArrayIterators are recommended for Large Data Sets. For simple-data foreach Loop is enough. Not sure about ArrayAccess , therefore ... – Rohit Chauhan Nov 30 '10 at 23:07

3 Answers3

5

There is no functional benefit, but structural.

If you define a map, you suggest, that it can contain an arbitrary number of named elements, that are of similar kinds. Object properties are usually well defined and of different types.

In short: If you implement ArrayAccess you say "My object (also) behaves like an array".

http://en.wikipedia.org/wiki/Associative_array

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
4

Well for a start it makes it easier/more natural to access members whose key does not form a valid identifier (e.g. contains awkward characters). For example, you can write $form['some-field'] instead of the more cumbersome $form->{'some-field'}.

Other than this, it's essentially the same as implementing the __get, __set, __isset, __unset magic methods, except allowing a different syntax (and with slightly different semantic connotations). See overloading.

Will Vousden
  • 32,488
  • 9
  • 84
  • 95
1

Using the Interfaces make more powerful tools, easier to use. I use it for collections, along with Iterator. It allows your object to act like an array even when it isn't. The power comes from not to map property name to an array element, but having the array access do something completely different.

i.e.

$users = new UserCollection();
$users->company = $companyid;
$user = $users[$userid];

// also
foreach( $users as $user ) {
  // Do something for each user in the system
}

In the first part, I'm creating a usercollection's object, and restricting its users list to that of a company id. Then when I access the collection, I get users with that id from that company. The second parts allows me to iterate over each user in a company.

Rahly
  • 1,462
  • 13
  • 16