Sample code for the iterator pattern of PHP classes

Source: Internet
Author: User
This is about PHP built-in interface iterator, PHP5 started to support the interface, and built-in iterator interface, so if you define a class, and implement the iterator interface, then your class object is Zend_iter_object, otherwise it is Zend_iter_plain_object.

For Zend_iter_plain_object classes, foreach obtains an array of default properties for the object through Hash_of, and then foreach the array.
For Zend_iter_object class objects, foreach is done by invoking the iterator interface-related functions implemented by the object, so for this question, the following answers can be made:

<?phpclass Sample implements Iterator{private $_items = Array (1,2,3,4,5,6,7);p ublic function __construct () {     ;// Void}public function Rewind () {Reset ($this->_items);} Public function current () {return current ($this->_items);} Public Function key () {return key ($this->_items);} Public function Next () {return next ($this->_items);} Public Function valid () {return ($this->current ()!== false);}} $sa = new sample (), foreach ($sa as $key = = $val) {print $key. "=". $val;}? >

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.