首页 > 代码库 > 使对象可以像数组一样进行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循环,要求属性必须是私有
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。