As I was studying the PHP SPL I came across the ArrayAccess class. I wondered what use it could possibly be since PHP’s array functionality is quite rich. So, I sent an email off to Lorna Jane, whom I met at this year’s PHP Community Conference held here in Nashville back in April. She gave me a very good explanation, so I decided to work up an example to cement the knowledge in my brain.
Since an example is worth a 1000 wordy descriptions, here is my Fruity example below.
First we need a basic object to describe a Fruit:
12345678910111213141516171819202122232425262728
# simple class to store a fruit string as a class propertyclassFruit{private$name=NULL;private$info=NULL;function__construct($fruit,$info){$this->set_fruit($fruit,$info);}functionget_name(){return$this->name;}functionget_info(){return$this->info;}functionset_fruit($name="no name",$info="no info"){$this->name=$name;$this->info=$info;}# a php "magic method" that allows a class to decide how# it will react when it is treated like a stringpublicfunction__toString(){return($this->get_name()." is ".$this->get_info());}}
Next we need a class that actually implements the ArrayAccess class that holds a collection of these Fruit objects:
Finally we need a little program that demonstrates how it all works together.
1234567891011121314151617181920
require_once("FruitAccess.php");# This example shows how to access objects as arrays using PHP's SPL$fruit_array=array("apple"=>"crunchy","orange"=>"tangy","banana"=>"yellow","grape"=>"small","cherry"=>"red");$fruit=newFruitAccess($fruit_array);echoPHP_EOL."Access the objects as a traditional array...".PHP_EOL;foreach($fruitas$key=>$value){echo$fruit["$key"].PHP_EOL;}echoPHP_EOL."...or use the Iterator implementation...".PHP_EOL;$fruit->rewind();while($fruit->valid()){echo$fruit->current().PHP_EOL;$fruit->next();}
All this code, if run from the command line, will product the following output:
Access the objects as a traditional array...
apple is crunchy
orange is tangy
banana is yellow
grape is small
cherry is red
...or use the Iterator implementation...
apple is crunchy
orange is tangy
banana is yellow
grape is small
cherry is red
You can download the source used in this posting: here