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? :)

2
  • Possible duplicate: stackoverflow.com/questions/4072927/… Commented Nov 30, 2010 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 ... Commented Nov 30, 2010 at 23:07

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Why the downvote? The answer is correct. I have upvoted again.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.