I am trying to understand the idea behind ArrayAccess Interface,
I dont understand what each method is about, If those methods(functions) are "built in" functions and ArrayAccess Interface(also "built in") is only "make sure" i am going to implement those "built in" methods(functions)
I am trying to understand what does each of thoes functions is doing with our code "Behind the scenes".
function offsetSet($offset, $value);
function offsetGet($offset);
function offsetUnset($offset);
function offsetExists($offset);
If i understand ArrayAccess is a Built In interface that Containing seals to implement, when we implement them we only implement references to thoes built in functions, I will be happy if some one can please help me get this right.
If you implement that interface, then the object acts like an array. e.g., if
$foo
is an instance of a class that implementsArrayAccess
:$foo['bar'] = 42
callsoffsetSet('bar', 42)
.echo $foo['bar']
callsoffsetGet('bar')
.unset($foo['bar'])
callsoffsetUnset('bar')
.isset($foo['bar'])
callsoffsetExists('bar')
.You never explicitly call the functions offset* yourself. It happens implicitly when you access the object as an array.
While comparing
ArrayAccess
toSimpleXMLElement
(an internal class not implementing it), I was curious, too. The interface is well documented in the manual already, so I wanted to highlight some differences in specific with offset types.But first of all a boilerplate example implementation of a class implementing
ArrayAccess
giving output when accessed:Running some usage-examples with it. I have left notes in form of comments. It should be pretty self-explaining:
Key differences to standard PHP arrays are that you can use not only integer and string as offsets.