美文网首页
7.12 遍历对象

7.12 遍历对象

作者: 57fc17b7d598 | 来源:发表于2017-07-01 17:08 被阅读14次

    通过 foreach 可以得到对象所有公开的属性,在类的内部还能获取到私有的和受保护的属性。

    通过实现 Iterator 接口,可以使得对象在被 foreach 循环时处理一些事情。

    // 定义类
    class Example implements Iterator{
        // 内部属性
        private $property = [];
        // 构造函数
        public function __construct(array $data){
            $this->property = $data;
        }
    
        // 初始化:重置指针,将指针移动到第一位,仅在foreach初始化时运行一次
        public function rewind(){
            echo "0.rewind <br /><hr />";
            reset($this->property);
        }
    
        // 第一步:验证当前指针指向的元素是否存在
        public function valid(){
            echo "1.valid <br />";
            return current($this->property);
        }
        // 第二步:获取当前指针指向的元素
        public function current(){
            echo "2.current <br />";
            $idx = current($this->property);
            echo "&nbsp;&nbsp; $idx <br />";
            return $idx;
        }
        // 第三步:获取当前指针指向的索引
        public function key(){
            echo "3.key <br />";
            $key = key($this->property);
            echo "&nbsp;&nbsp; $key <br />";
            return $key;
        }
        
    
        // 第四步:在foreach里循环
    
    
        // 第五步:指针往下移动一步
        public function next(){
            echo "5.next <br /> <hr />";
            return next($this->property);
        }
    }
    
    // 实例化
    $exam = new Example(['a' => 'php', 'b' => 'asp', 'c' => 'jsp']);
    // 循环遍历这个对象
    foreach ($exam as $key => $value) {
        echo "4.[$key : $value] <br />";
    }
    

    还一种方法,只需要返回一个 Iterator 类的实例即可。

    // 定义类
    class Example implements IteratorAggregate{
        // 私有属性
        private $array = [];
        // 构造函数
        public function __construct(array $array = []){
            $this->array = $array;
        }
        // 接口方法实现
        public function getIterator(){
            // 返回一个Iterator类的实例,此处用匿名类实现
            return new class($this->array) implements Iterator{
                private $data;
                public function __construct(array $data){
                    $this->data = $data;
                }
                public function rewind(){
                    reset($this->data);
                }
                public function valid(){
                    return current($this->data) !== false;
                }
                public function current(){
                    return current($this->data);
                }
                public function key(){
                    return key($this->data);
                }
                public function next(){
                    return next($this->data);
                }
            };
        }
    }
    
    // 实例化
    $exam = new Example(['a' => 'php', 'b' => 'asp', 'c' => 'jsp']);
    // 循环遍历这个对象
    foreach ($exam as $key => $value) {
        echo "$key : $value <br />";
    }
    

    相关文章

      网友评论

          本文标题:7.12 遍历对象

          本文链接:https://www.haomeiwen.com/subject/geqgcxtx.html