Iterator锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟接匡拷

(No version information available, might only be in Git)

锟斤拷锟�

锟斤拷锟斤拷锟节诧拷锟斤拷锟斤拷锟皆硷拷锟斤拷锟解部锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷慕涌凇锟�

锟接匡拷摘要

Iterator extends Traversable {
/* 锟斤拷锟斤拷 */
abstract public current ( void ) : mixed
abstract public key ( void ) : scalar
abstract public next ( void ) : void
abstract public rewind ( void ) : void
abstract public valid ( void ) : bool
}

预锟斤拷锟斤拷锟斤拷锟斤拷锟�

PHP 锟窖撅拷锟结供锟斤拷一些锟斤拷锟斤拷锟秸筹拷锟斤拷锟斤拷牡锟斤拷锟斤拷锟斤拷锟� 锟斤拷细锟叫憋拷渭锟� SPL 锟斤拷锟斤拷锟斤拷锟斤拷

锟斤拷锟斤拷

Example #1 锟斤拷锟斤拷锟矫凤拷

锟斤拷锟斤拷锟斤拷锟秸故撅拷锟绞癸拷锟� foreach 时锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟侥碉拷锟斤拷顺锟斤拷

<?php
class myIterator implements Iterator {
    private 
$position 0;
    private 
$array = array(
        
"firstelement",
        
"secondelement",
        
"lastelement",
    );  

    public function 
__construct() {
        
$this->position 0;
    }

    function 
rewind() {
        
var_dump(__METHOD__);
        
$this->position 0;
    }

    function 
current() {
        
var_dump(__METHOD__);
        return 
$this->array[$this->position];
    }

    function 
key() {
        
var_dump(__METHOD__);
        return 
$this->position;
    }

    function 
next() {
        
var_dump(__METHOD__);
        ++
$this->position;
    }

    function 
valid() {
        
var_dump(__METHOD__);
        return isset(
$this->array[$this->position]);
    }
}

$it = new myIterator;

foreach(
$it as $key => $value) {
    
var_dump($key$value);
    echo 
"\n";
}
?>

锟斤拷锟斤拷锟斤拷锟教碉拷锟斤拷锟斤拷锟斤拷锟斤拷冢锟�

string(18) "myIterator::rewind"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(0)
string(12) "firstelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(1)
string(13) "secondelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(2)
string(11) "lastelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"

Table of Contents

  • Iterator::current — 锟斤拷锟截碉拷前元锟斤拷
  • Iterator::key — 锟斤拷锟截碉拷前元锟截的硷拷
  • Iterator::next — 锟斤拷前锟狡讹拷锟斤拷锟斤拷一锟斤拷元锟斤拷
  • Iterator::rewind — 锟斤拷锟截碉拷锟斤拷锟斤拷锟斤拷锟侥碉拷一锟斤拷元锟斤拷
  • Iterator::valid — 锟斤拷榈鼻拔伙拷锟斤拷欠锟斤拷锟叫�