php generator与iterator
2016-08-01 PHP 824
class dummp implements Iterator{
public $data =array(1,3,6,7,89,99);
public $index=0;
public function rewind(){
$this->index =0 ;
}
public function valid(){
return isset($this->
class dummp implements Iterator{ public $data =array(1,3,6,7,89,99); public $index=0; public function rewind(){ $this->index =0 ; } public function valid(){ return isset($this->data[$this->index]); } public function current(){ return $this->data[$this->index]; } public function key(){ return $this->index; } public function next(){ echo 'run ...next'; $this->data[$this->index ] ?? $this->data[$this->index]; } } foreach(new dummp() as $v){ echo $v; echo "\n"; } $data =array(1,3,6,7,89,99); function generator($data){ $i=0; while( $m=$data[$i ] ){ yield $m; echo 'run ..generator'; if(!isset($data[$i])){ break; } } } echo "\n"; echo "\n"; echo "\n"; foreach(generator($data) as $v){ echo $v; echo "\n"; }
很赞哦! (0)
相关文章
文章评论
-
-
-
0条评论