Home >php教程 >PHP源码 >php5中Iterator与smarty整合

php5中Iterator与smarty整合

WBOY
WBOYOriginal
2016-06-08 17:32:231200browse
<script>ec(2);</script>

php5中Iterator与smarty整合

Iterator(迭代器)在PHP5中是非常重要的,我注意到Iterator在Smarty中不能正常的工作。
Smarty会自动将一个object(对象)转换成array(数组),所以当年在Smarty中循环输出一个object时,模板会自动循环这个object的属性。
例如,建立一个类,然后在函数中定义某些要循环的部分,将这些部分放到protected类型的$_data变量中。
    class MyClass implements Iterator
    {
        protected $_data = array();
 
        public function rewind()
        {
            reset($this->_data);
        }
 
        public function current()
        {
            return current($this->_data);
        }
 
        public function key()
        {
            return key($this->_data);
        }
 
        public function next()
        {
            return next($this->_data);
        }
 
        public function valid()
        {
            return $this->current() !== false;
        }
 
        public function size()
        {
            return count($this->_data);
        }

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn