Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /share/CACHEDEV1_DATA/Web/www/libraries/UBBcode/text_parser.class.php on line 228

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /share/CACHEDEV1_DATA/Web/www/libraries/UBBcode/text_parser.class.php on line 228
Implementing the ArrayAccess and Iterator interfaces in PHP

Comments Blog About Development Research Sites

Implementing the ArrayAccess and Iterator interfaces in PHP

Jan 23, 2008
After the previous entry a collegue pointed out that array operations on my dataset could also be achieved with the ArrayAccess interface. A bit of searching later told me that it would also require the Iterator interface for real niftyness, but that those two are really easy to implement!

So I modified my DatabaseResult class to extend a DatabaseResultArray, which weighs a slim 48 lines and allows pretty much every cool array operation on my result objects!
Code (php) (nieuw venster):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class DatabaseResultArray implements ArrayAccess, Iterator {
  
  private
$pointer = 0;

  public function
offsetExists ($index) {
    return isset(
$this -> objects[$index]);
  }

  public function
offsetGet ($index) {
    return
$this -> objects[$index];
  }

  public function
offsetSet ($index, $newValue) {
    $this -> objects[$index] = $newValue;
  }
  
  public function
offsetUnset ($index) {
    unset($this -> objects[$index]);
  }
  
  public function
key () {
    return
$this -> pointer;
  }
  
  public function
current () {
    return
$this -> objects[$this -> pointer];
  }
  
  public function
next () {
    $this -> pointer++;
  }
  
  public function
rewind () {
    $this -> pointer = 0;
  }
  
  public function
seek ($position) {
    $this -> pointer = $position;
  }
  
  public function
valid () {
    return isset(
$this -> objects[$this -> pointer]);
  }
}


As anyone can see the interfaces are very easy to implement: all you need is a pointer and an array of objects (or other elements of course) you wish to iterate over. The result of all this is that I can do now stuff like this:
Code (php) (nieuw venster):
1
2
3
4
5
global $context;
$menu = $context -> db -> menu;
foreach(
$menu -> name as $item) {
  echo
$item . ".
"
;
}

This will, as expected, neatly print out a list of menu item names!

The only downside is of course that the documentation for this feature is quite limited (link), but as with the session handler object anyone should be able to work them out with a few examples available.

FragFrog out!

New comment

Your name:
Comment: