php设计模式之迭代器模式

<?php

namespace Tools;

/*
迭代器模式
迭代器模式,在不需要了解内部实现的前提下,遍历一个聚合对象的内部元素
相比于传统的编程模式,迭代器模式可以影藏遍历元素的所需的操作
*/


class AllUser implements \Iterator{
	/*
	 * iterator接口中有5个方法,实现了iterator的类都可以foreach
	current()—返回当前元素值,
	key()—返回当前元素的键值,
	next()—下移一个元素,
	valid()—判定是否还有后续元素, 如果有, 返回true,
	rewind()—移到首元素.
	*/
	private $users = array();
	protected $index;

	public function __construct()
	{
		$db = mysqli_connect("localhost","root","","test");
		$res = $db->query("select * from user");
		$this->users = $res->fetch_all(MYSQLI_ASSOC);
	}

	//current()—返回当前元素值,
	public function current()
	{
		return $this->users[$this->index];
	}

	//key()—返回当前元素的键值,
	public function key()
	{
		return $this->index;
	}

	//next()—下移一个元素,
	public function next()
	{
		$this->index++;
	}

	//valid()—判定是否还有后续元素, 如果有, 返回true,
	public function valid()
	{
		return $this->index < count($this->users);
	}

	//rewind()—移到首元素.
	public function rewind()
	{
		$this->index = 0;
	}

}

$users = new \Tools\AllUser();
foreach($users as $user){
	print_r($user);
}



你可能感兴趣的:(php设计模式之迭代器模式)