PHP - Detailed explanation of IteratorAggregate interface

WBOY
Release: 2016-07-29 08:56:06
Original
1554 people have browsed it

PHP IteratorAggregate is also called an aggregate iterator. It provides an interface for creating external iterators. The interface summary is as follows:

IteratorAggregate extends Traversable {
	abstract public Traversable getIterator ( void )
}
Copy after login

When implementing the getIterator method, you must return an instance of a class that implements the Iterator interface.

Example description:

<?php
/**
 * 利用聚合式迭代器,并返回一个实现了Iterator接口的类的实例
 *
 * @author 疯狂老司机
 */
class myData implements IteratorAggregate {
    public $one = "Public property one";
    public $two = "Public property two";
    public $three = "Public property three";

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

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

$obj = new myData;

foreach($obj as $key => $value) {
    var_dump($key, $value);
    echo '<br>';// Linux:echo "\n";
}
?>
Copy after login
ArrayIterator iterator will encapsulate the object or array into a class that can be operated through foreach. The specific SPL iterator will be introduced in detail later.

The above introduces the detailed explanation of the PHP - IteratorAggregate interface, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!