PHP design pattern series-iterator

Source: Internet
Author: User
PHP iterator: helps construct specific objects that can provide a single standard interface to loop or iterate any type of counter data. (Not very common, in PHP) use cases: 1. access the content of an aggregate object without exposing its internal representation. 2. support for multiple aggregate objects... SyntaxHighlighter. all ();

PHP iterator:
It can help construct specific objects that can provide a single standard interface to loop or iterate any type of counter data. (Not very common, in PHP)
Use cases:
1. access the content of an aggregate object without exposing its internal representation.
2. supports multiple traversal of aggregate objects.
3. provides a unified interface (that is, multi-state iteration) for traversing different aggregation structures ).

PHP code implementation:
[Php]
// Iterator: helps construct specific objects that can provide a single standard interface to loop or iterate any type of counter data
Class MyIterator implements Iterator {

Private $ var = array ();

Public function _ construct ($ array ){
$ This-> var = $ array;
}

Public function rewind (){
Reset ($ this-> var );
}

Public function current (){
$ Var = current ($ this-> var );
Return $ var;
}

Public function valid (){
$ Var = $ this-> current ()! = False;
Return $ var;
}

Public function next (){
$ Var = next ($ this-> var );
Return $ var;
}

Public function key (){
$ Var = key ($ this-> var );
Return $ var;
}
}
$ Values = array ('A', 'B', 'C ');
$ It = new MyIterator ($ values );
Foreach ($ it as $ a =>$ B ){
Print "$ a: $ B
";
}
?>


Author: initphp

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.