首頁  >  文章  >  後端開發  >  PHP設計模式 迭代器模式

PHP設計模式 迭代器模式

WBOY
WBOY原創
2016-07-29 08:57:41839瀏覽

迭代器模式,在不需要了解內部實作的前提下,遍歷一個聚合物件的內部元素。相較於傳統的程式模式,迭代器模式可以隱藏遍歷元素所需的操作。

AllHacl.php

<?<span>php

namespace Baobab;


</span><span>class</span> AllHacl <span>implements</span><span> \iterator{

    </span><span>protected</span><span>$ids</span><span>;</span><span>protected</span><span>$index</span>;<span>//</span><span>当前位置</span><span>function</span><span> __construct(){
        </span><span>$db</span> = Factory::getDatabase('ha_cl'<span>);
        </span><span>$result</span> = <span>$db</span>->query('select ID from ha_cl'<span>);
        </span><span>$this</span>->ids = <span>$result</span>-><span>fetch_all(MYSQLI_ASSOC);
    }<br><span>/*<span>*<br>   * 返回当前元素<br><span>*/</span></span></span></span><span>function</span><span>current</span><span>(){
        </span><span>$id</span> = <span>$this</span>->ids[<span>$this</span>->index]['ID'<span>];
        </span><span>return</span> Factory::getHacl(<span>$id</span><span>);
   }<br><span><span>/*<span>*<br>   * 向前移动到下一个元素<br><span>*/</span></span></span></span></span><span>function</span><span>next</span><span>(){
        </span><span>$this</span>->index ++<span>;
    }

    </span><span>/*</span><span>*
     * 返回到迭代器的第一个元素
     </span><span>*/</span><span>function</span><span>rewind</span><span>(){
        </span><span>$this</span>->index = 0<span>;
    }

    </span><span>/*</span><span>*
     * 查询当前位置是否有数据
     </span><span>*/</span><span>function</span><span> valid(){
        </span><span>return</span><span>$this</span>->index - <span>count</span>(<span>$this</span>-><span>ids);
    }<br><span><span>/*<span>*<br>   * 返回当前元素的键<br><span>*/</span></span></span></span></span><span>function</span><span>key</span><span>(){
        </span><span>return</span><span>$this</span>-><span>index;
    }
}</span>

index.php

<span>$hacls</span> = <span>new</span><span> \Baobab\AllHacl();
</span><span>foreach</span>(<span>$hacls</span><span>as</span><span>$hacl</span><span>){
    </span><span>var_dump</span>(<span>$hacl</span>-><span>haclname);
}</span>

Hacl類相關內容參考資料物件映射模式。 http://www.cnblogs.com/tianxintian22/p/5232016.html

以上就介紹了PHP設計模式 迭代器模式,包含了面向的內容,希望對PHP教學有興趣的朋友有幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn