mirror of
https://github.com/sigmasternchen/php-doc-en
synced 2025-03-16 00:48:54 +00:00
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
This commit is contained in:
parent
c24a2f41cd
commit
3109183fde
1 changed files with 30 additions and 18 deletions
|
@ -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) {
|
|||
<screen role="php">
|
||||
<![CDATA[
|
||||
rewinding
|
||||
current: 1
|
||||
valid: 1
|
||||
current: 1
|
||||
key: 0
|
||||
0: 1
|
||||
next: 2
|
||||
current: 2
|
||||
valid: 1
|
||||
current: 2
|
||||
key: 1
|
||||
1: 2
|
||||
next: 3
|
||||
current: 3
|
||||
valid: 1
|
||||
current: 3
|
||||
key: 2
|
||||
2: 3
|
||||
next:
|
||||
current:
|
||||
valid:
|
||||
next: (no more)
|
||||
valid:
|
||||
]]>
|
||||
</screen>
|
||||
|
||||
|
|
Loading…
Reference in a new issue