当前位置: 网学 > 编程文档 > PHP > 正文

PHP设计模式之迭代器模式的深入解析

来源:Http://myeducs.cn 联系QQ:点击这里给我发消息 作者: 用户投稿 来源: 网络 发布时间: 13/06/18
* Usually IteratorAggregate is the interface to implement.
* It has only one method, which must return an Iterator
* already defined as another class (e.g. ArrayIterator)
* Iterator gives a finer control over the algorithm,
* because all the hook points of Iterator'' contract
* are available for implementation.
*/
class NumbersSet implements IteratorAggregate
{
private PHP设计模式之迭代器模式的深入解析_网学
浏览:
版权所有 QQ:3710167 邮箱:3710167@qq.com 网学网 [Myeducs.cn] 您电脑的分辨率是 像素
Copyright 2008-2015 myeducs.Cn www.myeducs.Cn All Rights Reserved
湘ICP备09003080号
content;

public function __construct(array $content)
{
$this->_content = $content;
}

public function contains($number)
{
return in_array($number, $this->_content);
}

/**
* Only this method is necessary to implement IteratorAggregate.
* @return Iterator
*/
public function getIterator()
{
return new ArrayIterator($this->_content);
}
}

echo "NumbersSet: ";
foreach (new NumbersSet($array) as $key => $value) {
echo "$key => $value. ";
}
echo "\n";
// let''s play with RecursiveIterator implementations
$it = new RecursiveArrayIterator(array(
''A'',
''B'',
array(
''C'',
''D''
),
array(
array(
''E'',
''F''
),
array(
''G'',
''H'',
''I''
)
)
));
// $it is a RecursiveIterator but also an Iterator,
// so it loops normally over the four elements
// of the array.
echo "Foreach over a RecursiveIterator: ";
foreach ($it as $value) {
echo $value;
// but RecursiveIterators specify additional
// methods to explore children nodes
$children = $it->hasChildren() ? ''{Yes}'' : ''{No}'';
echo $children, '' '';
}
echo "\n";
// we can bridge it to a different contract via
// a RecursiveIteratorIterator, whose cryptic name
// should be read as ''an Iterator that spans over
// a RecursiveIterator''.
echo "Foreach over a RecursiveIteratorIterator: ";
foreach (new RecursiveIteratorIterator($it) as $value) {
echo $value;
}
echo "\n";

网学推荐

免费论文

原创论文

浏览:
设为首页 | 加入收藏 | 论文首页 | 论文专题 | 设计下载 | 网学软件 | 论文模板 | 论文资源 | 程序设计 | 关于网学 | 站内搜索 | 网学留言 | 友情链接 | 资料中心
版权所有 QQ:3710167 邮箱:3710167@qq.com 网学网 [Myeducs.cn] 您电脑的分辨率是 像素
Copyright 2008-2015 myeducs.Cn www.myeducs.Cn All Rights Reserved
湘ICP备09003080号