Iterators in PHP

Source: Internet
Author: User

<?PHPclassMyiteratorImplementsIterator {Private $position= 0; Private $array=Array(        "Firstelement", "Secondelement", "Lastelement",    );  Public function__construct () {$this->position = 0; }    function Rewind() {       Var_dump(__method__); $this->position = 0; }    function  Current() {       Var_dump(__method__); return' One_ '.$this-Array[$this->position]. ' _two '; }    function Key() {       Var_dump(__method__); return $this-position; }    function Next() {        Var_dump(__method__); ++$this-position; }    functionvalid () {Var_dump(__method__); return isset($this-Array[$this-position]); }}$it=NewMyiterator;foreach($it  as $key=$value) {    //var_dump ($key, $value);    Echo $value; Echo"\ n";}

From the execution results above, the workflow of the iterator is this:
1. First point to array first
2. Determine whether it is valid
3. Get the current value
4. Get the current key
5. Enter the loop to perform the current pointer plus one operation
6. Whether the judgment is valid (invalid stop)
7. Get the current value
8. Get the current key
9. Repeat 5 Steps


Why use iterators?
In this example, the object is encapsulated to simplify the complexity of the foreach statement, or to focus on the process, while the details are given to the iterator.
The iterator itself is implemented through the C extension, so the traversal and PHP itself provided by the iterator is a performance difference of the second, because the traversal is an object rather than an array, we have encountered a lot of trouble in the traversal, even if we solve, there is no guarantee that we apply to the algorithm is the best

Iterators in PHP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.