ArrayAccess PHP Interface
OOP, PHP
The PHP ArrayAccess class is an interface that allows objects to be accessed as arrays.
Classes that extend the ArrayAccess
interface must include four core methods:
When the ArrayAccess
class is implemented by a child class with the appropriate methods, data held in the resulting object can be accessed using array syntax.
Background: PHP Arrays
Arrays in PHP are really ordered maps - a data type that associates keys and values.
…This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
PHP arrays hold groups of values which can be identified by position or an associative index.
Associative array:
Numerically Indexed Array:
Background: PHP Objects
PHP Objects incorporate one or more functions (methods) along with data (properties) into a structure called a class. Many objects can be instantiated from a single class - the class simply provides the blueprint for the object. Classes are defined with the class
keyword, and new objects are instantiated from classes using the new keyword.
PHP also includes a generic empty class called stdClass
- which can be useful for anonymous objects and dynamic properties. This kind of class is useful for storing key-value pairs. You could do this in an array, but value objects have some advantages.
The stdClass
class can be used to create stand-alone objects without first defining a class.
Value Object Example:
Output:
The same thing can be achieved by means of an associative array:
The output is the same as the object example, though there is more leeway with the key names, which can contain spaces:
There are a few ways of creating a stdClass object in modern PHP:
Mistake pointed out by Rajesh in comments:
Array Access
It can sometimes be useful to access objects as arrays. ArrayAccess
is a built in interface class that allows this.
The interface requires that extending classes use these methods:
ArrayAccess::offsetExists
ArrayAccess::offsetGet
ArrayAccess::offsetSet
ArrayAccess::offsetUnset
The methods allow us to define a handy data container which can be accessed and amended using the array syntax.
ArrayAccess: Simple Implementation
This allows us to access the Object data structure using array syntax:
The Updated object:
References
- Dynamic Properties in PHP and StdClass
- Article on PHP ArrayAccess interface
- S.O. question: Value objects vs associative arrays in PHP
See Also:
comments powered by Disqus