Home > Article > Backend Development > PHP manual learning iterator Iterator
<?php #迭代器原理演示 class MyIterator implements Iterator{ #定义一个属性,原来记录执行次数 private $pos; #定义要遍历的数组 private $arr=array( 'first_param', 'secnod_param', 'third_param' ); #定义构造函数 public function __construct(){ $this->pos = 0; } #定义指针置0 rewind public function rewind(){ echo __METHOD__,"<br/>"; $this->pos=0; } #定义valid 方法 public function valid(){ #判断是否可行 echo __METHOD__,"<br/>"; if(isset($this->arr[$this->pos])){ return isset($this->arr[$this->pos]); } } #获取当前的值 current public function current(){ echo __METHOD__,"<br/>"; return $this->arr[$this->pos]; } #获取当前的键值 key public function key(){ echo __METHOD__,"<br/>"; return $this->pos; } #指针下移函数 public function next(){ echo __METHOD__,"<br/>"; ++$this->pos; } } #实例化对象 $test = new MyIterator(); #遍历对象 foreach($test as $key=>$val){ var_dump($key,$val); echo '<hr/>'; }
The above introduces the Iterator learned in the PHP manual, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.