[PHP] object Traversal

Source: Internet
Author: User

We know that in PHP, foreach can easily perform iterative operations on iterative structures (such as arrays and objects:

foreach( $array as $elem){var_dump($elem);}
foreach($obj as $key=>$value){echo "$key=>$value".PHP_EOL;}

So we thought: What will happen if we perform the foreach operation on an instantiated object?

First, we define the basic class as follows:

Class Test{/* one public variable */public $a;public $b;/* one private variable */private $c;public function __construct(){$this->a = "public";$this->b = "public";$this->c = "private";}public function traverseInside(){foreach($this as $key=>$value){echo $key."=>".$value.EOL;}}}

Then we instantiate the class, iterate it, and compare it with the results of the internal iteration:

$test = new Test;echo "

The iteration result is:

It can be seen that the external foreach loop only loops through the public attributes of the object, while the external foreach cannot loops through the private attributes. Therefore, if we want to loop out all the attributes (public and private) of the class through foreach outside, it is impossible to rely solely on foreach. We must "modify" the class ". How to transform the class? If you understand the implementation of foreach (refer to laruence's blog: http://www.laruence.com/2008/11/20/630.html), you can easily find the corresponding solution. On the other hand, the design pattern-the basis for reusable object-oriented software design also mentions that by separating Object Access and traversal from objects and putting them into an iterator object, the iterator mode allows you to traverse objects in different ways. We will not go into the meaning of this sentence for the time being. As long as we know, we can use the iterator to traverse the object.

In the <pre-defined interface> section of the PHP manual, the following interface must be implemented in the iteratable object to implement the iterator mode:

abstractpublicmixedcurrent( void )abstractpublicscalarkey( void )abstractpublicvoidnext( void )abstractpublicvoidrewind( void )abstractpublicbooleanvalid( void )

With this. It is convenient to implement the iterator mode. A simple example is as follows:

class TestIterator implements Iterator {    private $point = 0;    private $data = array(        "one","two","three",    );      public function __construct() {        $this->point = 0;    }    function rewind() {        $this->point = 0;    }    function current() {        return $this->data[$this->point];    }    function key() {        return $this->point;    }    function next() {        ++$this->point;    }    function valid() {        return isset($this->data[$this->point]);    }}$it = new TestIterator;foreach($it as $key => $value) {    echo $key, $value;    echo "\n";}

Of course, objects using the iterator can be traversed as follows:

$it = new TestIterator;$it->rewind();while ($it->valid()){    $key = $it->key();    $value = $it->current();    echo "$key=>$value";    $it->next();}

Finally, we attached the implementation of listiterator in yii (as the name suggests, the iterator that implements the list iteration operation:

<?php/** * CListIterator class file. * * @author Qiang Xue <qiang.xue@gmail.com> * @link http://www.yiiframework.com/ * @copyright Copyright  2008-2011 Yii Software LLC * @license http://www.yiiframework.com/license/ *//** * CListIterator implements an interator for {@link CList}. * * It allows CList to return a new iterator for traversing the items in the list. * * @author Qiang Xue <qiang.xue@gmail.com> * @version $Id$ * @package system.collections * @since 1.0 */class CListIterator implements Iterator{/** * @var array the data to be iterated through */private $_d;/** * @var integer index of the current item */private $_i;/** * @var integer count of the data items */private $_c;/** * Constructor. * @param array $data the data to be iterated through */public function __construct(&$data){$this->_d=&$data;$this->_i=0;$this->_c=count($this->_d);}/** * Rewinds internal array pointer. * This method is required by the interface Iterator. */public function rewind(){$this->_i=0;}/** * Returns the key of the current array item. * This method is required by the interface Iterator. * @return integer the key of the current array item */public function key(){return $this->_i;}/** * Returns the current array item. * This method is required by the interface Iterator. * @return mixed the current array item */public function current(){return $this->_d[$this->_i];}/** * Moves the internal pointer to the next array item. * This method is required by the interface Iterator. */public function next(){$this->_i++;}/** * Returns whether there is an item at current position. * This method is required by the interface Iterator. * @return boolean */public function valid(){return $this->_i<$this->_c;}}

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.