Manuel PHP

The Iterator interface

Introduction

Interface for external iterators or objects that can be iterated themselves internally.

Synopsis de la classe

Iterator
Iterator implements Traversable {
/* Methods */
abstract public mixed Iterator::current ( void )
abstract public scalar Iterator::key ( void )
abstract public void Iterator::next ( void )
abstract public void Iterator::rewind ( void )
abstract public boolean Iterator::valid ( void )
}

Exemple #1 Basic usage

This example demonstrates in which order methods are called when foreach()ing over an iterator.

  1. <?php
  2. class myIterator implements Iterator { 
  3.    private $position = 0; 
  4.    private $array = array( 
  5.       "firstelement", 
  6.       "secondelement", 
  7.       "lastelement", 
  8.    ); 
  9.  
  10.    public function __construct() { 
  11.       $this->position = 0; 
  12.    } 
  13.  
  14.    function rewind() { 
  15.       var_dump(__METHOD__); 
  16.       $this->position = 0; 
  17.    } 
  18.  
  19.    function current() { 
  20.       var_dump(__METHOD__); 
  21.       return $this->array[$this->position]; 
  22.    } 
  23.  
  24.    function key() { 
  25.       var_dump(__METHOD__); 
  26.       return $this->position; 
  27.    } 
  28.  
  29.    function next() { 
  30.       var_dump(__METHOD__); 
  31.       ++$this->position; 
  32.    } 
  33.  
  34.    function valid() { 
  35.       var_dump(__METHOD__); 
  36.       return isset($this->array[$this->position]); 
  37.    }  
  38. }  
  39.  
  40. $it = new myIterator;  
  41.  
  42. foreach($it as $key => $value) { 
  43.    var_dump($key, $value); 
  44.    echo "\n";  
  45. }  
  46. ?> 

L'exemple ci-dessus va afficher quelque chose de similaire à :

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"

Sommaire


Remonter Remonter
L'éditeur javascript - CSS - Gentoo - Tutoriaux PHP - Tutoriels PHP - Bretagne - php - Moto