zoukankan      html  css  js  c++  java
  • php设计模式-迭代器

    class CustomIterator implements Iterator
    {
        private $_data;
        private $_index = 0;
    
        public function __construct($data)
        {
            $this->_data = $data;
        }
    
        /**
         * 返回当前指针指向的元素
         * @return mixed
         */
        public function current()
        {
            return $this->_data[$this->_index];
        }
    
        /**
         * 指针向前推一位
         */
        public function next()
        {
            $this->_index ++;
        }
    
        /**
         * 重置指针,将指针指向第一个元素
         */
        public function rewind()
        {
            $this->_index = 0;
        }
    
        /**
         * 返回当前指针位置
         * @return int|mixed
         */
        public function key()
        {
            return $this->_index;
        }
    
        /**
         * 检测指针当前指向是否有效
         * @return bool
         */
        public function valid()
        {
            return count($this->_data) > $this->_index;
        }
    }
    
    $data = array(
        ['name' => 'zhangsan', 'age' => 12, 'career' => 'engineer'],
        ['name' => 'lisi', 'age' => 12, 'career' => 'engineer'],
        ['name' => 'waner', 'age' => 12, 'career' => 'engineer'],
        ['name' => 'faguan', 'age' => 12, 'career' => 'engineer'],
    );
    
    $obj = new CustomIterator($data);
    
    echo '<pre>';
    foreach ($obj as $key => $user) {
        print_r($user);
    }
    
    echo '---------------------------------------------------<br>';
    // 重置指针,相当于数组里的reset()方法
    $obj->rewind();
    
    while ($obj->valid())
    {
        print_r($obj->current());
        $obj->next();
    }
    

      结果:

    Array
    (
        [name] => zhangsan
        [age] => 12
        [career] => engineer
    )
    Array
    (
        [name] => lisi
        [age] => 12
        [career] => engineer
    )
    Array
    (
        [name] => waner
        [age] => 12
        [career] => engineer
    )
    Array
    (
        [name] => faguan
        [age] => 12
        [career] => engineer
    )
    ---------------------------------------------------
    Array
    (
        [name] => zhangsan
        [age] => 12
        [career] => engineer
    )
    Array
    (
        [name] => lisi
        [age] => 12
        [career] => engineer
    )
    Array
    (
        [name] => waner
        [age] => 12
        [career] => engineer
    )
    Array
    (
        [name] => faguan
        [age] => 12
        [career] => engineer
    )
    

      

  • 相关阅读:
    springMVC中添加<mvc:resource>时的问题
    package
    mybatis 解决属性名和字段名不一致
    Linux常用命令
    Hibernate下载
    Hibernate初识
    js根据身份证获取出生年月日
    spring-Boot 热部署
    Struts2---动态action以及应用
    Struts2基础
  • 原文地址:https://www.cnblogs.com/xiangdongsheng/p/13353295.html
Copyright © 2011-2022 走看看