对于ZEND_ITER_PLAIN_OBJECT的类,foreach会通过HASH_OF获取该对象的默认属性数组,然后对该数组进行 foreach.
而对于ZEND_ITER_OBJECT的类对象,则会通过调用对象实现的Iterator接口相关函数来进行foreach, 所以, 对于这道笔试题, 可以作出如下的答案:
<?php 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; } ?>
以上就是详解php类的Iterator模式的示例代码的详细内容,更多请关注php中文网其它相关文章!