From 3109183fdea39696558e7b89b26f885a72b3724b Mon Sep 17 00:00:00 2001 From: Sean Coates Date: Wed, 28 Jul 2010 02:59:12 +0000 Subject: [PATCH] fix the iterator implementation. If the array contains a value of false, the previous implementation would bail (the valid() function issues current() which returns false, just as if the array returns false; the new implementation keeps its own index, so there's no need to use current(). git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@301637 c90b9560-bf6c-de11-be94-00142212c4b1 --- language/oop5/iterations.xml | 48 ++++++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 18 deletions(-) diff --git a/language/oop5/iterations.xml b/language/oop5/iterations.xml index 69f38eb727..e67162552b 100644 --- a/language/oop5/iterations.xml +++ b/language/oop5/iterations.xml @@ -82,6 +82,7 @@ private => private var class MyIterator implements Iterator { private $var = array(); + private $index = 0; public function __construct($array) { @@ -90,34 +91,49 @@ class MyIterator implements Iterator } } - public function rewind() { + public function rewind() + { echo "rewinding\n"; - reset($this->var); + $this->index = 0; } - public function current() { - $var = current($this->var); + public function current() + { + $k = array_keys($this->var); + $var = $this->var[$k[$this->index]]; echo "current: $var\n"; return $var; } - public function key() { - $var = key($this->var); + public function key() + { + $k = array_keys($this->var); + $var = $k[$this->index]; echo "key: $var\n"; return $var; } - public function next() { - $var = next($this->var); - echo "next: $var\n"; - return $var; + public function next() + { + $k = array_keys($this->var); + if (isset($k[++$this->index])) { + $var = $this->var[$k[$this->index]]; + echo "next: $var\n"; + return $var; + } else { + echo "next:\n"; + return false; + } } - public function valid() { - $var = $this->current() !== false; + public function valid() + { + $k = array_keys($this->var); + $var = isset($k[$this->index]); echo "valid: {$var}\n"; return $var; } + } $values = array(1,2,3); @@ -133,26 +149,22 @@ foreach ($it as $a => $b) {