php iterator,PHP遍历接口Iterator详解

从手册中查到的解释是:

Iterator extends Traversable {

/* Methods */

abstract public mixed current ( void )

abstract public scalar key ( void )

abstract public void next ( void )

abstract public void rewind ( void )

abstract public boolean valid ( void )

}

当一个实现了Iterator接口的对象,被foreach遍历时,会自动调用这些方法。调用的循序是:

rewind() -> valid() -> current() -> key() -> next()

下面来看一下简单的代码:

class myIterator implements Iterator {

private $position = 0;

private $array = array(

"firstelement",

"secondelement",

"lastelement",

);

public function __construct() {

$this->position = 0;

}

function rewind() {

var_dump(__METHOD__);

$this->position = 0;

}

function current() {

var_dump(__METHOD__);

return $this->array[$this->position];

}

function key() {

var_dump(__METHOD__);

return $this->position;

}

function next() {

var_dump(__METHOD__);

++$this->position;

}

function valid() {

var_dump(__METHOD__);

return isset($this->array[$this->position]);

}

}

$it = new myIterator;

foreach($it as $key => $value) {

var_dump($key, $value);

echo '---------------------------'."\n";

}

以上会输出:

/Users/thanatos/Web/study/blean.php:15:string 'myIterator::rewind' (length=18)

/Users/thanatos/Web/study/blean.php:35:string 'myIterator::valid' (length=17)

/Users/thanatos/Web/study/blean.php:20:string 'myIterator::current' (length=19)

/Users/thanatos/Web/study/blean.php:25:string 'myIterator::key' (length=15)

/Users/thanatos/Web/study/blean.php:43:int 0

/Users/thanatos/Web/study/blean.php:43:string 'firstelement' (length=12)

---------------------------

/Users/thanatos/Web/study/blean.php:30:string 'myIterator::next' (length=16)

/Users/thanatos/Web/study/blean.php:35:string 'myIterator::valid' (length=17)

/Users/thanatos/Web/study/blean.php:20:string 'myIterator::current' (length=19)

/Users/thanatos/Web/study/blean.php:25:string 'myIterator::key' (length=15)

/Users/thanatos/Web/study/blean.php:43:int 1

/Users/thanatos/Web/study/blean.php:43:string 'secondelement' (length=13)

---------------------------

/Users/thanatos/Web/study/blean.php:30:string 'myIterator::next' (length=16)

/Users/thanatos/Web/study/blean.php:35:string 'myIterator::valid' (length=17)

/Users/thanatos/Web/study/blean.php:20:string 'myIterator::current' (length=19)

/Users/thanatos/Web/study/blean.php:25:string 'myIterator::key' (length=15)

/Users/thanatos/Web/study/blean.php:43:int 2

/Users/thanatos/Web/study/blean.php:43:string 'lastelement' (length=11)

---------------------------

/Users/thanatos/Web/study/blean.php:30:string 'myIterator::next' (length=16)

/Users/thanatos/Web/study/blean.php:35:string 'myIterator::valid' (length=17)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值