首页 > 代码库 > 使对象可以像数组一样进行foreach循环,要求属性必须是私有

使对象可以像数组一样进行foreach循环,要求属性必须是私有

 

 

1 Iterator extends Traversable {
2 /* Methods */
3 abstract public mixed current ( void )
4 abstract public scalar key ( void )
5 abstract public void next ( void )
6 abstract public void rewind ( void )
7 abstract public boolean valid ( void )
8 }

所以, 对于这道笔试题, 可以作出如下的答案:

 1 class sample implements Iterator
 2 {
 3     private $_items = array(1,2,3,4,5,6,7);
 4     public function __construct() {
 5                   ;//void
 6     }
 7     public function rewind() { reset($this->_items); }
 8     public function current() { return current($this->_items); }
 9     public function key() { return key($this->_items); }
10     public function next() { return next($this->_items); }
11     public function valid() { return ( $this->current() !== false ); }
12 }
13 $sa = new sample();
14 foreach($sa as $key => $val){
15     print $key . "=>" .$val;
16 }

————————————————————————————————————————————

 

php5里面已经有了iterator接口,只要实现该接口,即可以实现对象私有属性被foreach遍历

 1 <?php
 2 class Sample implements iterator{
 3   private $var = array(1,2,3,4,5);
 4   public function __construct(){}
 5   public function rewind(){ reset($this->var);}
 6   public function current(){return current($this->var);}
 7   public function key(){return key($this->var);}
 8   public function next(){return next($this->var);}
 9   public function valid(){return ($this->current()!==false);}
10 }
11 $s = new Sample();
12 foreach($s as $k=>$v){ echo $k.‘=‘.$v.‘<br/>‘;}
13 ?>

 

使对象可以像数组一样进行foreach循环,要求属性必须是私有