array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'fr', ), 'this' => array ( 0 => 'class.iterator.php', 1 => 'Iterator', ), 'up' => array ( 0 => 'reserved.interfaces.php', 1 => 'Interfaces et Classes Prédéfinies', ), 'prev' => array ( 0 => 'class.traversable.php', 1 => 'Traversable', ), 'next' => array ( 0 => 'iterator.current.php', 1 => 'Iterator::current', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'fr', 'path' => 'language/predefined/iterator.xml', ), 'extra_header_links' => array ( 'rel' => 'alternate', 'href' => '/manual/en/feeds/class.iterator.atom', 'type' => 'application/atom+xml', ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); ?>
(PHP 5, PHP 7, PHP 8)
Interface pour les itérateurs ou les objets externes qui peuvent être itérés eux-mêmes en interne.
PHP fournit quelques itérateurs pour certaines tâches. Voir les itérateurs SPL pour une liste complète.
Exemple #1 Exemple simple
Cet exemple montre l'ordre d'appel des méthodes lors d'un appel à l'instruction foreach sur un itérateur.
<?php
class myIterator implements Iterator {
private $position = 0;
private $array = array(
"premierelement",
"secondelement",
"dernierelement",
);
public function __construct() {
$this->position = 0;
}
public function rewind(): void {
var_dump(__METHOD__);
$this->position = 0;
}
#[\ReturnTypeWillChange]
public function current() {
var_dump(__METHOD__);
return $this->array[$this->position];
}
#[\ReturnTypeWillChange]
public function key() {
var_dump(__METHOD__);
return $this->position;
}
public function next(): void {
var_dump(__METHOD__);
++$this->position;
}
public function valid(): bool {
var_dump(__METHOD__);
return isset($this->array[$this->position]);
}
}
$it = new myIterator;
foreach($it as $key => $value) {
var_dump($key, $value);
echo "\n";
}
?>
Résultat de l'exemple ci-dessus est similaire à :
string(18) "myIterator::rewind" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(0) string(12) "premierelement" 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) "dernierelement" string(16) "myIterator::next" string(17) "myIterator::valid"
Voir aussi l'itération d'objet.