Home  >  Article  >  Backend Development  >  php iterator what does it mean

php iterator what does it mean

藏色散人
藏色散人Original
2021-10-15 10:37:051891browse

php Iterator is a PHP design pattern, which refers to an interface that can iterate its own external iterator or class internally; the iterator pattern can traverse an aggregate object without knowing the internal implementation. internal elements.

php iterator what does it mean

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

What does php iterator mean?

PHP iterator mode

Iterator: The class inherits the Iterator interface of PHP and operates in batches.

1. Iterator mode traverses the internal elements of an aggregate object without knowing the internal implementation.

2. Compared with traditional programming patterns, the iterator pattern can hide the operations required to traverse elements.

InterfaceIterator

current() Returns the current element

key() Returns the key of the current element

next() Moves forward to the next element

rewind() returns the first element of the iterator

class AllUser implements \Iterator
{
    protected $index = 0;
    protected $data = [];
    public function __construct()
    {
        $link = mysqli_connect('192.168.0.91', 'root', '123', 'xxx');
        $rec = mysqli_query($link, 'select id from doc_admin');
        $this->data = mysqli_fetch_all($rec, MYSQLI_ASSOC);
    }
    //1 重置迭代器
    public function rewind()
    {
        $this->index = 0;
    }
xxx
    //2 验证迭代器是否有数据
    public function valid()
    {
        return $this->index < count($this->data);
    }
    //3 获取当前内容
    public function current()
    {
        $id = $this->data[$this->index];
        return User::find($id);
    }
    //4 移动key到下一个
    public function next()
    {
        return $this->index++;
    }
    //5 迭代器位置key
    public function key()
    {
        return $this->index;
    }
}
//实现迭代遍历用户表
$users = new AllUser();
//可实时修改
foreach ($users as $user){
    $user->add_time = time();
    $user->save();
}

Iterator interface: https://www.php.net/manual/zh/class .iterator.php

Recommended study: "PHP Video Tutorial"

The above is the detailed content of php iterator what does it mean. For more information, please follow other related articles on the PHP Chinese website!

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