Mimicking an array in PHP
Today I was experimenting with PHP5’s magic methods, and I found myself wanting an extra one, something like __getIndex(), so that I can have an object mimic an array whilst doing other stuff aswell. Sort of like Django’s QuerySet’s.
Well, I didn’t find it, but I did find a nfity way to have an object emulate an array. It makes use of extending PHP’s ArrayObject, and overriding the functionality you need.
If you want to simply allow the object to have indexes set on it, you can just extend the ArrayObject class, like so:
class QuerySet extends ArrayObject{
}
Then you can do stuff like:
$q = new QuerySet();
$q['hi'] = 'hello';
echo $q['hi'];
>>> hello
If you want to wrap another array inside your object, like I want to do with having tuples inside a relation, you can override the functions you need and delegate them to the wrapped array.
Here’s my short example.
class QuerySet extends ArrayObject{
private $wrapped_array;
public function __construct(){
//Create a blank array
$this->wrapped_array = array();
}
//Called when you access the object like an array
public function offsetGet($index){
return $this->wrapped_array[$index];
}
//Returns a count
public function count(){
return count($this->wrapped_array);
}
//Returns the iterator so you can do foreach(QuerySet...
public function getIterator(){
$array_obj = new ArrayObject($this->wrapped_array);
return $array_obj->getIterator();
}
}
I’ve only used a few here, but the whole object is documented here, so it’d be best to implement all the functions you need.
I found this really handy in doing some lazy evaluation stuff, very similar to the way Django implements it’s QuerySet’s.

Comments
Subscribe Make comment