Usage Analysis of PHP Aggregated Iterator Interface IteratorAggregate
- 2021-08-31 07:27:06
- OfStack
This article illustrates the use of PHP aggregate iterator interface IteratorAggregate. Share it for your reference, as follows:
PHP IteratorAggregate, also known as aggregated iterators, provides an interface for creating external iterators, which is summarized as follows:
IteratorAggregate extends Traversable {
abstract public Traversable getIterator ( void )
}
You must return an instance of a class that implements the Iterator interface when implementing the getIterator method.
Example illustration:
<?php
/**
* Take advantage of the aggregated iterator and return the 1 Realized Iterator An instance of the class of the interface
*
* @author Crazy old driver
*/
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";
}
?>
The above example outputs:
string 'one' (length=3)
string 'Public property one' (length=19)
string 'two' (length=3)
string 'Public property two' (length=19)
string 'three' (length=5)
string 'Public property three' (length=21)
string 'last' (length=4)
string 'last property' (length=13)
ArrayIterator iterator will encapsulate objects or arrays into a class that can be operated by foreach. For details, please refer to the introduction of SPL iterator. For interested friends, please refer to https://www.ofstack.com/article/43074. htm.
For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"
I hope this article is helpful to everyone's PHP programming.