Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of ArrayAccess Interface in PHP?

Tags:

arrays

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

like image 944
Rohit Chauhan Avatar asked Dec 28 '22 04:12

Rohit Chauhan


1 Answers

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

like image 200
KingCrunch Avatar answered Jan 08 '23 11:01

KingCrunch