Iterator, à quoi cela sert'il ?
Si je m'en tiens au code suivant:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| <?php
class Validator implements Iterator
{ private $curr,$start,$end,$function ;
function __construct($start ,$end , $function, $param1)
{ $this->start = $start ;
$this->end = $end ;
$this->function = $function ;
$this->param = $param1 ;
$this->rewind() ;
}
function rewind() {
$this->curr = $this->start ;
}
function key() {
return($this->curr) ;
}
function current() {
return( call_user_func_array( $this->function, array($this->curr, $this->param) ) ) ;
}
function next() {
if ($this->valid())
$this->curr++ ;
}
function valid() {
return( ($this->curr <= $this->end) ? true : false ) ;
}
}
function power($x,$p) {
return( pow($x,$p) ) ; }
$val = new Validator(3,7, "power" , 2) ;
/*
foreach ($val as $key => $value)
{ print("the square of $key is $value<br>\n") ; }
*/
?> |
Dans lequel, j'ai mis le foreach en commmentaire et bien RIEN ne se passe.....
A quoi peut bien servir de se fatiguer à définir une classe iterator, à quoi celle-ci peut-elle bien servir ???:calim2:
Dans l'instanciation de l'object Validitor, je donne les bornes inférieur et supérieur ainsi que le fonction a appliquer...càd exactement la copie conforme du foreach !
Je ne vois pas l'intérêt de la classe Iterator même si cet exemple est juste pour l'exercice.....