fork download
  1. <?php
  2. class IteratorTest implements ArrayAccess, Iterator {
  3. private $pointer = 0;
  4. private $objects = array();
  5.  
  6. public function offsetExists($index) {
  7. return isset($this->objects[$index]);
  8. }
  9.  
  10. public function offsetGet($index) {
  11. return $this->objects[$index];
  12. }
  13.  
  14. public function offsetSet($index, $newValue) {
  15. $this->objects[$index] = $newValue;
  16. }
  17.  
  18. public function offsetUnset($index) {
  19. unset($this->objects[$index]);
  20. }
  21.  
  22. public function key() {
  23. return key($this->objects);
  24. }
  25.  
  26. public function current() {
  27. return current($this->objects);
  28. }
  29.  
  30. public function next() {
  31. next($this->objects);
  32. }
  33.  
  34. public function rewind() {
  35. reset($this->objects);
  36. }
  37.  
  38. public function valid() {
  39. return current($this->objects);
  40. }
  41. }
  42.  
  43. $it = new IteratorTest();
  44.  
  45. $it['one'] = 1;
  46. $it['two'] = 2;
  47.  
  48. foreach ($it as $k => $v) {
  49. echo "$k: $v\n";
  50. }
  51.  
  52. // expected result:
  53. // one: 1
  54. // two: 2
Success #stdin #stdout 0.02s 13112KB
stdin
Standard input is empty
stdout
one: 1
two: 2