<?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/>'; }
时间: 2024-10-25 02:22:35