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

admin3年前PHP教程34

说明

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聚合式迭代器是什么内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

免责声明:本文内容来自用户上传并发布,站点仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。请核实广告和内容真实性,谨慎使用。

相关文章

江西gpu服务器租用费用跟哪些因素有关

GPU服务器租用费用是一个复杂的问题,因为它涉及到多个因素。下面是一些影响GPU服务器租用费用的因素:GPU型号不同的GPU型号具有不同的性能和价格。更高性能的GPU通常价格更高。例如,NVIDIAT...

PHP将amr音频文件转换为mp3格式的操作细节

说下整体思路1、服务器安装ffmpeg2、使用ffmpeg -i 指令来转换amr为mp3格式(这个到时候写在PHP代码中,使用exec函数执行即可)3、在网页端使用HTML5的audio标签来播放m...

Fatal error: 'break' not in the 'loop' or 'switch' context in Function.php

今天本地改代码改完做测试发现现在的文件中打开是Break' not in the 'loop' or 'switch' context“这样的;当时...

PHP的runkit扩展如何使用

目录动态修改常量安装查看超全局变量键方法相关操作类方法相关操作总结动态修改常量define('A', 'TestA'); runkit_constant_re...

php桥接模式的实例用法及代码分析

说明1、将两个原本不相关的类结合在一起,然后利用两个类中的方法和属性,输出一份新的结果。2、结构分为Abstraction抽象类、RefindAbstraction被提炼的抽象类、Implemento...

php封装pdo实例以及pdo长连接的优缺点总结

一、前言最近需要写脚本来实现崩溃日志的入库,不出所料又是脱离于框架的,那么行吧,咱们只能自己封装数据库相关操作了。博主这里选择了封装pdo操作数据库相关。二、为什么选择pdo众所周知的,php在早期的...