之前用java写过迭代设计模式,个人觉得PHP这个迭代没撒子使用作用
<?php
class collection implements Iterator {
//被迭代数组
private $_iterator_arr;
//索引值
private $_index = 0;
public function __construct($arr){
$this->_iterator_arr = $arr;
}
public function __destruct(){
}
/*
* 验证当前是否有值
* @author lichaoyong 2014-04-18 16:36:28
*/
public function valid(){
return isset($this->_iterator_arr[$this->_index]);
}
/**
* 返回当前索引的值
* @author lichaoyong 2014-04-18 16:37:26
*/
public function current(){
return $this->_iterator_arr[$this->_index];
}
/**
* 返回当前的索引
* @author lichaoyong 2014-04-18 16:38:25
*/
public function key(){
return $this->_index;
}
/**
* 返回下一个索引
* @author lichaoyong 2014-04-18 16:39:04
*/
public function next(){
$this->_index++;
}
/**
* 把索引指向第一个单元
* @author lichaoyong 2014-04-18 16:45:17
*/
public function rewind(){
$this->_index = 0 ;
}
/**
* 返回最后一个单元
* @author lichaoyong 2014-04-18 16:47:37
*/
public function end(){
return end($this->_iterator_arr);
}
}
?>
<?php
/**
* 程序主入口
* @author lichaoyong 2014-04-18 16:15:17
*
* 迭代器设计模式
*/
class main{
public function main(){
$array = array('A', 'B', 'C', 'D'=>array(1));
echo "Collection: ";
$coll_arr = new collection($array);
$coll_arr->next();
echo $coll_arr->rewind();
echo $coll_arr->current();
echo $coll_arr->end();
}
}
?>