微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php迭代器模式(iterator pattern)

。。。

<?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"

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐