实现 IteratorAggregate接口

<?php


class MyIterator implements Iterator{


private $var = array();

public function __construct($array){

if(is_array($array)){

$this->var = $array;

}

}

public function rewind(){

 

reset($this->var);

}
public function current(){

$var = current($this->var);

 

return $var;

}

public function key(){

$var = key($this->var);

 

return $var;


}

public function next(){

$var = next($this->var);


return $var;

}

public function valid(){

$var = $this->current() !== false;

 

return $var;


}

}

class Myclloection implements IteratorAggregate{


private $items = array();

private $count = 0;


public function getIterator(){

return new MyIterator($this->items);

}

public function add ($value){

$this->items[$this->count++] = $value;

}

}

$coll = new Myclloection();

$coll->add('value1');
$coll->add('value2');
$coll->add('value3');

foreach ($coll as $key =>$val){

echo "key/value: [$key -> $val]<br>";

}

?>

posted on 2018-04-25 23:17  paulversion  阅读(147)  评论(0编辑  收藏  举报