1.使对象可以像数组一样进行foreach循环,要求属性必须是私有。(Iterator模式的PHP5实现,写一类实现Iterator接口)
<?php class Test implements Iterator{ private $item = array('id'=>1,'name'=>'php'); public function rewind(){ reset($this->item); } public function current(){ return current($this->item); } public function key(){ return key($this->item); } public function next(){ return next($this->item); } public function valid(){ return($this->current()!==false); } } //测试 $t=new Test; foreach($t as $k=>$v){ echo$k,'--->',$v,'<br/>'; } ?>
2.用PHP实现一个双向队列
<?php class Deque{ private $queue=array(); public function addFirst($item){ return array_unshift($this->queue,$item); } public function addLast($item){ return array_push($this->queue,$item); } public function removeFirst(){ return array_shift($this->queue); } public function removeLast(){ return array_pop($this->queue); } } ?>