PHP:Iterator(迭代器)接口和生成器
迭代器
可在内部迭代自己的外部迭代器或类的接口。详情:http://php.net/manual/zh/class.iterator.php
接口摘要
Iterator extends Traversable {
/* 方法 */
abstract public mixed current ( void )
abstract public scalar key ( void )
abstract public void next ( void )
abstract public void rewind ( void )
abstract public bool valid ( void )
}
- Iterator::current — 返回当前元素
- Iterator::key — 返回当前元素的键
- Iterator::next — 向前移动到下一个元素
- Iterator::rewind — 返回到迭代器的第一个元素
- Iterator::valid — 检查当前位置是否有效
基本用法:
<?php
class myIterator implements Iterator {
private $position = 0;
private $array = array(
"firstelement",
"secondelement",
"lastelement",
);
public function __construct() {
$this->position = 0;
}
function rewind() {
$this->position = 0;
}
function current() {
return $this->array[$this->position];
}
function key() {
return $this->position;
}
function next() {
++$this->position;
}
function valid() {
return isset($this->array[$this->position]);
}
}
$it = new myIterator;
foreach($it as $key => $value) {
echo "$key=>$value\n";
}
?>
下面用迭代器来实现一个斐波纳契数列:
<?php
class myIterator implements Iterator {
private $position = 0;
private $current=1;
private $prev=0;
public function __construct() {
$this->position = 0;
}
public function rewind() {
$this->position = 0;
$this->current=1;
$this->prev=0;
}
public function current() {
return $this->current;
}
public function key() {
return $this->position;
}
public function next() {
$tem=$this->prev;
$this->prev=$this->current;
$this->current=$this->current+$tem;
++$this->position;
}
public function valid() {
return ($this->current!==false);
}
}
$it = new myIterator;
foreach($it as $key => $value) {
if($key>15) break;
echo "$value ";
}
?>
返回结果:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
生成器
生成器提供了一种更容易的方法来实现简单的对象迭代,相比较定义类实现 Iterator 接口的方式,性能开销和复杂性大大降低。
生成器允许你在 foreach 代码块中写代码来迭代一组数据而不需要在内存中创建一个数组, 那会使你的内存达到上限,或者会占据可观的处理时间。相反,你可以写一个生成器函数,就像一个普通的自定义函数一样, 和普通函数只返回一次不同的是, 生成器可以根据需要 yield 多次,以便生成需要迭代的值。
写一个斐波纳契数列生成器,代码如下:
<?php
function gen() {
$current=1;
$prev=0;
while ($current){
yield $current;
$temp=$current;
$current=$current+$prev;
$prev=$temp;
}
}
foreach (gen() as $k=>$v){
if($k>15) break;
echo "$v ";
}
结果
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

浙公网安备 33010602011771号