PHP迭代器的内部执行过程详解
代码如下: class myIterator implements Iterator { private $position = 0; private $array = array( "first_element", "second_element", "last_element", ); public function __construct() { function rewind() { function current() { function key() { function next() { function valid() { $it = new myIterator; foreach($it as $key => $value) { 程序运行输出: 代码如下: string(18) "myIterator::rewind" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" 输出键值:int(0) string(13) "first_element" string(16) "myIterator::next" string(16) "myIterator::next" string(16) "myIterator::next" 一般的迭代器内部需要下面的方法: Iterator::current — Return the current element 返回当前元素 Iterator::key — Return the key of the current element 返回当前元素的键 Iterator::next — Move forward to next element 移向下一个元素 Iterator::rewind — Rewind the Iterator to the first element 重新回到第一个元素 Iterator::valid — Checks if current position is valid 检查当前位置的有效性 如果不是很清楚迭代器的内容工作流程,可以查看下面的迭代器对数组的遍历过程: 代码如下: /** * @author 简明现代魔法 http://www.nowamagic.net */ class MyIterator implements Iterator { private $var = array(); public function __construct($array) public function rewind() { public function current() { public function key() { public function next() { public function valid() { $values = array(1,2,3); foreach ($it as $k => $v) { 程序运行结果: 代码如下: 倒回第一个元素 当前元素: 1 检查有效性: 1 当前元素: 1 当前元素的键: 0 此时键值对 -- key 0: value 1 移向下一个元素: 2 移向下一个元素: 3 移向下一个元素: 现在就很清晰了吧? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |