zoukankan      html  css  js  c++  java
  • PHP5实现foreach语言结构遍历一个类的实例

    PHP5实现foreach语言结构遍历一个类

    创建一个类集成Iterator接口,并实现Iterator里面的方法即可,下面见实例代码实现

    <?php
    class Test implements Iterator
    {
        public $item = null;
        public $step = 0;
        public $key = 0;
        public function __construct(array $item=array())
        {
            $this->setItem($item);
        }
    
        public function setItem($item=array())
        {
            // 设置对象属性
            $this->item = $item?$item:range(1,8);
            return $this;
        }
        public function next()
        {
            $this->step = $this->step+1;
            echo "当前第{$this->step}步,执行".__METHOD__."方法<br>";
            ++$this->key;
            // 设置下次指针
        }
    
        public function current()
        {
            $this->step = $this->step+1;
            echo "当前第{$this->step}步,执行".__METHOD__."方法<br>";
            return $this->item[$this->key];
            // 返回当前指针的值
        }
    
        public function valid()
        {
            $this->step = $this->step+1;
            echo "当前第{$this->step}步,执行".__METHOD__."方法<br>";
            return isset($this->item[$this->key]);
            // 验证当前指针的值是否存在
        }
        public function rewind()
        {
            $this->step = $this->step+1;
            echo "当前第{$this->step}步,执行".__METHOD__."方法<br>";
            $this->key = 0;
            // 指针的重置
        }
        public function key()
        {
            $this->step = $this->step+1;
            echo "当前第{$this->step}步,执行".__METHOD__."方法<br>";
            return $this->key;
            // 返回当前指针
        }
    }
    
    $test = new Test();
    foreach($test as $i){
        echo $i."<br/>";
    }

    输出结果如下:

      

  • 相关阅读:
    搜索区间
    搜索插入位置
    旋转排序数组
    搜索二维矩阵
    njnja 安装
    rpmbuild打包
    snappy 安装
    mysql8 安装
    re2c安装
    make 安装
  • 原文地址:https://www.cnblogs.com/bafeiyu/p/10536898.html
Copyright © 2011-2022 走看看