Iterator & user functions
Trouvé:
Voici une solution (il y en a peut être d'autres)
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 44 45 46 47 48 49
|
class myIterator implements Iterator
{ private $start, $end, $function ;
public function __construct( $start, $end , $function )
{ $this->curr = $this->start = $start ;
$this->end = $end ;
$this->function = $function ;
}
/**
* Iterator methods
*
*/
function rewind() {
$this->curr = $this->start ;
}
function key() {
return($this->curr) ;
}
function current() {
return( call_user_func( $this->function, $this->key() ) ) ;
}
function next() {
if ($this->valid())
$this->curr++ ;
}
function valid() {
return( ($this->curr <= $this->end) ? true : false ) ;
}
/**
* End of Iterator methods
*
*/
}
function myFunction($param)
{ return(pow($param,2)) ; }
$array = new myIterator( 10, 15 , "myFunction" );
while($array->valid() )
{ print("the power of " . $array->key() . " is " . $array->current() . "<br>\n") ;
$array->next() ;
} |
Voilà, merci de me tenir informé si + simple ou + performant :D:D