소개
반복자 인터페이스 확장 추상 순회 가능 상호 작용. PHP는 많은 내장 반복기(SPL 반복기라고 함)를 제공합니다. ) 많은 일상적인 기능에 사용됩니다. 예는 ArrayIterator입니다. , DirectoryIterator 등. Iterator 인터페이스를 구현하는 사용자 클래스는 정의된 대로 추상 메소드를 구현해야 합니다.
구문
Iterator extends Traversable {
/* Methods */
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
} 방법
Iterator::current — 현재 요소를 반환합니다.
Iterator::key — 현재 요소의 키를 반환합니다.
Iterator::next — 다음 요소로 앞으로 이동
Iterator::rewind — Iterator를 첫 번째 요소로 되감습니다.
Iterator::valid — 현재 위치가 유효한지 확인합니다.
IteratorAggregate를 구현할 때 또는 반복자 Traversable을 확장하는 인터페이스는 구현에서 이름 앞에 나열되어야 합니다. 조항.
반복자 예
다음 PHP 스크립트에서 Interface를 구현하는 클래스는 배열을 private 변수로 포함합니다. Iterator의 추상 메서드를 구현하면 foreach를 사용하여 배열을 탐색할 수 있습니다. next()와 함께 루프 방법.
예시
<?php
class myIterator implements Iterator {
private $index = 0;
private $arr = array(10,20,30,40);
public function __construct() {
$this->index = 0;
}
public function rewind() {
$this->index = 0;
}
public function current() {
return $this->arr[$this->index];
}
public function key() {
return $this->index;
}
public function next() {
++$this->index;
}
public function valid() {
return isset($this->arr[$this->index]);
}
}
?> foreach 사용 루프에서 MyIterator 개체의 배열 속성을 반복할 수 있습니다.
$it = new myIterator();
foreach($it as $key => $value) {
echo "$key=>". $value ."\n";
} next()를 클릭하여 반복을 수행할 수도 있습니다. while 루프의 메서드. 되감기하세요. 루프 시작 전의 반복자
예시
$it->rewind();
do {
echo $it->key() . "=>" .$it->current() . "\n";
$it->next();
}
while ($it->valid()); 출력
두 경우 모두 배열 속성을 탐색하면 다음 결과가 표시됩니다.
0=>10 1=>20 2=>30 3=>40