• 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
    )
    

      

  • 相关阅读:
    Linux系统备份与还原
    今后的日程安排(面试期间)
    我的下一份工作是什么样子呢?
    WebView 放大缩小
    Android EditText赋值后光标在后面
    android中捕捉menu按键的点击事件
    Android控件常用属性
    点击autocompletetextview时,如果没有输入时显示默认列表
    在Activity里怎样获得另一个xml布局文件的控件
    Android中的AutoCompleteTextView的使用
  • 原文地址:https://www.cnblogs.com/xiangdongsheng/p/13353295.html
Copyright © 2020-2023  润新知