。。。
<?php
/*
The iterator pattern is used to traverse a container and access its elements. In
other words, one class becomes able to traverse the elements of another class.
The PHP has a native support for the iterator as part of built in \Iterator and
\IteratorAggregate interfaces.
*/
class ProductIterator implements \Iterator {
private $position = 0;
private $productsCollection;
public function __construct(ProductCollection
$productsCollection) {
$this->productsCollection = $productsCollection;
}
public function current() {
return $this->productsCollection->
getProduct($this->position);
}
public function key() {
return $this->position;
}
public function next() {
$this->position++;
}
public function rewind() {
$this->position = 0;
}
public function valid() {
return !is_null($this->productsCollection->
getProduct($this->position));
}
}
class ProductCollection implements \IteratorAggregate {
private $products = array();
public function getIterator() {
return new ProductIterator($this);
}
public function addProduct($string) {
$this->products[] = $string;
}
public function getProduct($key) {
if (isset($this->products[$key])) {
return $this->products[$key];
}
return null;
}
public function isEmpty() {
return empty($products);
}
}
$products = new ProductCollection();
$products->addProduct('T-Shirt Red<br/>');
$products->addProduct('T-Shirt Blue<br/>');
$products->addProduct('T-Shirt Green<br/>');
$products->addProduct('T-Shirt Yellow<br/>');
foreach ($products as $product) {
var_dump($product);
}
?>
输出:
string(16) "T-Shirt Red
" string(17) "T-Shirt Blue
" string(18) "T-Shirt Green
" string(19) "T-Shirt Yellow
"
来源:https://www.cnblogs.com/aguncn/p/11184436.html