zoukankan      html  css  js  c++  java
  • php迭代器

    迭代器实现代码

    <?php
    class myIterator implements Iterator
    {
        public $position = 0 ;
        public $arr = array('one','two','three','four','five','six');
     
        public function __construct()
        {
            $this->position = 0;
        }
     
        public function rewind()
        {
            var_dump(__METHOD__);
            $this->position = 0 ;
        }
     
        public function current()
        {
            var_dump(__METHOD__);
            return $this->arr[$this->position] ;
        }
     
        public function key()
        {
            var_dump(__METHOD__);
            return $this->position;
        }
     
        public function next()
        {
            var_dump(__METHOD__);
            ++$this->position;
        }
        public function valid()
        {
            var_dump(__METHOD__);
            return isset($this->arr[$this->position]);
        }
    }
     
    $it = new myIterator;
    foreach($it as $key=>$value)
    {
        var_dump($key,$value);
        echo "</br>";
    }

    遍历迭代器时内部执行流程

    string(18) "myIterator::rewind" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(0) string(3) "one" 
    string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(1) string(3) "two" 
    string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(2) string(5) "three" 
    string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(3) string(4) "four" 
    string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(4) string(4) "five" 
    string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(5) string(3) "six" 
    string(16) "myIterator::next" string(17) "myIterator::valid"
  • 相关阅读:
    安装devstack之配置proxy
    设备信息表项目
    好的运维工程师
    rhel 6.4 增加光盘为yum repo
    深度运维产品工具关键词
    坚持是一种能力
    书单 电影单 电视剧单
    三日不读书,便觉得言语无味,面目可憎
    STAR法则
    【断舍离】
  • 原文地址:https://www.cnblogs.com/zxqblogrecord/p/9364768.html
Copyright © 2011-2022 走看看