normally using java. I ve seen a snippet like this today
$oStrategie = new Strategie();
foreach($aData as $key=>$value) {
$oStrategie[$key] = $value;
}
$oStrategie->doSomething()
Strategie is a selfmade php class with nothing special. simple constructor doing nothing important and so on.
in the class Strategie the method doSomething() accesses the ArrayValues of $aData
$this['array_index_1']
Why can i access the array there even if the Strategie class doesent have any attributes defined and no setter overwritten or something like that? Can anybody explain me whats happening there? Is there no need to have attributes in the class in php???
Your class implements the
ArrayAccessinterface. This means it implements the following methods:This allows you to use array access
$var[$offset]on instances of this class. Here’s a standard implement of a class like this, using a$containerarray to hold properties:Without looking at the actual implementation of
Strategieor the class it’s derived from, it’s hard to tell what it’s actually doing.But using this, you can control the behavior of the class, for example, when accessing an offset that doesn’t exist. Suppose we replace
offsetGet($offset)with:Now whenever we try to access an offset that doesn’t exist, it will return a default (eg:
$this->default) and log an error, for example.Note that you can accomplish similar behavior using the magic methods
__set(),__get(),__isset()and__unset(). The difference between the magic methods I just listed andArrayAccessis that you’d access a property via$obj->propertyrather than$obj[offset]