php迭代器模式(iterator pattern)
发布时间:2020-12-13 16:07:52 所属栏目:PHP教程 来源:网络整理
导读:。。。 ? php /* The iterator pattern is used to traverse a container and access its elements. Inother 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
。。。 <?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" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |