开发者

Benefits of ArrayAccess Interface in PHP?

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  $开发者_Go百科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? :)


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜