码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-02-06 23:23:04      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:void   echo   pre   next   bool   end   span   bsp   str   

 

 

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循环,要求属性必须是私有

标签:void   echo   pre   next   bool   end   span   bsp   str   

原文地址:http://www.cnblogs.com/gengyi/p/6372006.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!