华域联盟 PHP php聚合式迭代器的基础知识点及实例代码

php聚合式迭代器的基础知识点及实例代码

文章目录[隐藏]

说明

1、实现其他迭代器功能的接口,相当于在其他迭代器上安装一个外壳,只有一种方法。

2、聚合迭代器可以与许多迭代器结合,实现更高效的迭代。

实例

class MainIterator implements Iterator
{
    private $var = array();
    public function __construct($array)    //构造函数, 初始化对象数组
    {
        if (is_array($array)) {
        $this->var = $array;
        }
    }
 
    public function rewind() {   
        echo "rewinding\n";
        reset($this->var);    //将数组的内部指针指向第一个单元
    }
 
    public function current() {
        $var = current($this->var);    // 返回数组中的当前值
        echo "current: $var\n";
        return $var;
    }
 
    public function key() {
        $var = key($this->var);       //返回数组中内部指针指向的当前单元的键名
        echo "key: $var\n";
        return $var;
    }
 
    public function next() {
        $var = next($this->var);     //返回数组内部指针指向的下一个单元的值
        echo "next: $var\n";
        return $var;
    }
 
    public function valid() {
    return !is_null(key($this->var); //判断当前单元的键是否为空
    }
}

内容扩展:

<?php
class myData implements IteratorAggregate {
    public $property1 = "Public property one";
    public $property2 = "Public property two";
    public $property3 = "Public property three";

    public function __construct() {
        $this->property4 = "last property";
    }

    public function getIterator() {
        return new ArrayIterator($this);
    }
}

$obj = new myData;

foreach($obj as $key => $value) {
    var_dump($key, $value);
    echo "\n";
}
?>

以上例程的输出类似于:

string(9) "property1"
string(19) "Public property one"

string(9) "property2"
string(19) "Public property two"

string(9) "property3"
string(21) "Public property three"

string(9) "property4"
string(13) "last property"

到此这篇关于php聚合式迭代器的基础知识点及实例代码的文章就介绍到这了,更多相关php聚合式迭代器是什么内容请搜索华域联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持华域联盟!

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » php聚合式迭代器的基础知识点及实例代码

转载请保留出处和原文链接:https://www.cnhackhy.com/79400.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部