Enables an object to be a foreach loop like an array, requiring that the property be private

Source: Internet
Author: User
Tags rewind

1Iteratorextendstraversable {2 /*Methods*/3 Abstract  Public Mixed  Current(void)4 Abstract  PublicScalarKey(void)5 Abstract  PublicvoidNext(void)6 Abstract  PublicvoidRewind(void)7 Abstract  Public Booleanvalid (void)8}

Therefore, for this question, the following answers can be made:

1 classSampleImplementsIterator2 {3     Private $_items=Array(1,2,3,4,5,6,7);4      Public function__construct () {5;//void6     }7      Public function Rewind() {Reset($this-_items); }8      Public function  Current() {return  Current($this-_items); }9      Public function Key() {return Key($this-_items); }Ten      Public function Next() {return Next($this-_items); } One      Public functionValid () {return($this- Current() !==false ); } A } - $sa=Newsample (); - foreach($sa  as $key=$val){ the     Print $key. "=".$val; -}

————————————————————————————————————————————

PHP5 already has the iterator interface, as long as the implementation of the interface, that is, you can implement the object private property is foreach traversal

1<?PHP2 classSampleImplementsiterator{3 Private $var=Array(1,2,3,4,5);4      Public function__construct () {}5      Public function Rewind(){Reset($this-var);}6      Public function  Current(){return  Current($this-var);}7      Public function Key(){return Key($this-var);}8      Public function Next(){return Next($this-var);}9      Public functionValid () {return($this- Current()!==false);}Ten } One $s=NewSample (); A foreach($s  as $k=$v){Echo $k.‘ = '.$v.‘ <br/> ';} -?>

Enables an object to be a foreach loop like an array, requiring that the property be private

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.