PHP内置接口Iterator
PHP的内置接口Iterator了,PHP5开始支持了接口, 并且内置了Iterator接口, 所以如果你定义了一个类,并实现了Iterator接口,那么你的这个类对象就是ZEND_ITER_OBJECT,否则就是ZEND_ITER_PLAIN_OBJECT.
对于ZEND_ITER_PLAIN_OBJECT的类,foreach会通过HASH_OF获取该对象的默认属性数组,然后对该数组进行foreach.
而对于ZEND_ITER_OBJECT的类对象,则会通过调用对象实现的Iterator接口相关函数来进行foreach, 所以, 对于这道笔试题, 可以作出如下的答案:
- class sample implements Iterator
- {
- private $_items = array(1,2,3,4,5,6,7);
- public function __construct() {
- ;//void
- }
- public function rewind() { reset($this->_items); }
- public function current() { return current($this->_items); }
- public function key() { return key($this->_items); }
- public function next() { return next($this->_items); }
- public function valid() { return ( $this->current() !== false ); }
- }
- $sa = new sample();
- foreach($sa as $key => $val){
- print $key . "=>" .$val;
- }