Home  >  Article  >  Backend Development  >  PHP manual learning iterator Iterator

PHP manual learning iterator Iterator

WBOY
WBOYOriginal
2016-08-08 09:28:271070browse
<?php 

#迭代器原理演示
class MyIterator implements Iterator{
	#定义一个属性,原来记录执行次数
	private $pos;
	#定义要遍历的数组
	private $arr=array(
		&#39;first_param&#39;,
		&#39;secnod_param&#39;,
		&#39;third_param&#39;
	);


	#定义构造函数
	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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn