<?php
//IteratorAggregate Generators
//事例(一)
class Language implements IteratorAggregate{
private $names;
public function __construct(){
$this->names = explode(',','PHP,JS,JAVA,GO');
}
public function getIterator(){
return new ArrayIterator($this->names);
}
}
$langs = new Language();
foreach($langs as $lang){
echo $lang.PHP_EOL;
}
//事例(二) 返回一个外部迭代器,可以对数据本身及相关逻辑做更统一的封装
class Test implements IteratorAggregate{
private $data;
public function __construct(array $data){
$this->data = $data;
}
public function getIterator(){
foreach($this->data as $key=>$value){
yield $key=>$value;
}
}
}
$testArr = array(
'xd'=>100,
'action'=>123,
'xingd'=>126
);
$test = new Test($testArr);
foreach($test as $key=>$value){
echo $key.'-'.$value.PHP_EOL;
}
已有 0 条评论