PHP pre-defined interface _ PHP Tutorial

Source: Internet
Author: User
Tags rewind
PHP predefined interface. PHP pre-defined interface introduction there are several pre-defined interfaces in PHP. it is also useful for IteratorAggregate (Iterator of aggregate Iterator) IteratorAggregateextendsTraversable PHP pre-defined interface
Introduction

PHP has several predefined interfaces, which are quite useful.

IteratorAggregate (aggregate Iterator)

IteratorAggregate extends Traversable {

Abstract public Traversable getIterator (void)

}

This interface implements a function-create an external iterator. how can we understand it? if we use foreach to traverse objects, if we do not inherit the IteratorAggregate interface, traverse all the public attributes of an object (only in the form of public $ var ). If IteratorAggregate is inherited, the object returned by the getIterator method implemented in the class is used. Note that the returned object must be a Traversable object or an object extended from the Traversable object. Otherwise, an exception is thrown.

// See the example class My {private $ _ data = ['a' => 'Yan ruitao', 'B' => 'yanruitao ', 'C' => 'Lulu',]; public function getIterator () {return new ArrayIterator ($ this-> _ data) ;}}$ obj = new My; foreach ($ obj as $ key = >$ value) {echo "$ key => $ value \ n ";} // the output result is empty class My implements IteratorAggregate {private $ _ data = ['a' => 'Yan ruitao', 'B' => 'yanruitao ', 'C' => 'Lulu',]; public function getIterator () {return new ArrayIterator ($ this-> _ data) ;}}$ obj = new My; foreach ($ obj as $ key = >$ value) {echo "$ key => $ value \ n";} // result: a => Yan Rutao B => yanruitaoc => LULUCountableCountable {abstract public int count (void )}

This interface is used to count the number of objects. how can we understand it? when we call count for an object, if the function does not inherit Countable, 1 is always returned, if Countable is inherited, the number returned by the implemented count method is returned. let's take a look at the following example:

Class CountMe {protected $ _ myCount = 3; public function count () {return $ this-> _ myCount ;}}$ countable = new CountMe (); echo count ($ countable); // returns 1 class CountMe implements Countable {protected $ _ myCount = 3; public function count () {return $ this-> _ myCount ;}} $ countable = new CountMe (); echo count ($ countable); // returns 3 ArrayAccessArrayAccess {abstract public boolean offsetExists (mixed $ offset) abstract public mixed offsetGet (mixed $ offset) public void offsetSet (mixed $ offset, mixed $ value) public void offsetUnset (mixed $ offset )}

The function of this interface is to allow us to access objects just like accessing arrays. So what should we do? I guess it's true that if php encounters the array method to use objects during lexical analysis, go back to the object to check whether ArrayAccess is implemented. If yes, perform the corresponding operations (set, unset, isset, and get). In this way, we can place an array in the class, let the class implement the basic operation of the array method. The following is an example:

Class myObj {} $ obj = new myObj; $ obj ['name']; // Fatal error: cannot use object of type myObj as array in class myObj implements ArrayAccess {public function offsetSet ($ offset, $ value) {echo "offsetSet: {$ offset }=>{$ value} \ n ";} public function offsetExists ($ offset) {echo" offsetExists: {$ offset} \ n ";} public function offsetUnset ($ offset) {echo "offsetUnset: {$ offset} \ n";} public function offsetGet ($ offset) {echo "offsetGet: {$ offset} \ n ";}}$ obj = new myObj; $ obj [1] = 'Yan Ruitao '; isset ($ obj ['name']); unset ($ obj ['name']); $ obj ['yrt ']; // output result: offsetSet: 1 => Yan Ruitao offsetExists: nameoffsetUnset: nameoffsetGet: yrtclass myObj implements ArrayAccess {private $ _ data = []; public function offsetSet ($ offset, $ value) {$ this-> _ data [$ offset] = $ value ;} public function offsetExists ($ offset) {return isset ($ this-> _ data [$ offset]);} public function offsetUnset ($ offset) {unset ($ this-> _ data [$ offset]);} public function offsetGet ($ offset) {return $ this-> _ data [$ offset];} $ obj = new myObj; $ obj ['yrt '] = 'Yan Ruitao'; var_dump ($ obj ['yrt ']); var_dump (isset ($ obj ['yrt ']); unset ($ obj ['yrt']); var_dump (isset ($ obj ['yrt ']); var_dump ($ obj ['yrt ']); // output: string (9) "Yan Ruitao" bool (true) bool (false) Notice: Undefined index: yrt // The last one will report that the objects on the Notice can only be basic array operations, not even traversal. combined with the previous IteratorAggregate, you can perform foreach: class myObj implements ArrayAccess, iteratorAggregate {private $ _ data = []; public function getIterator () {return new ArrayIterator ($ this-> _ data );}......} $ obj = new myObj; $ obj ['yrt '] = 'Yan Ritao'; $ obj [1] = 'Yan Ritao '; $ obj ['name'] = 'Yan Ruitao '; $ obj ['age'] = 23; foreach ($ obj as $ key => $ value) {echo "{$ key }=>{$ value} \ n" ;}// output: yrt => Yan Ritao 1 => Yan Ritao name => Yan Ritao age => 23 IteratorIterator extends Traversable {abstract public mixed current (void) abstract public scalar key (void) abstract public void next (void) abstract public void rewind (void) abstract public boolean valid (void )}

The external iterator or class interface can be iterated internally. this is an explanation provided in the official document. it is still hard to understand. In fact, I feel that the functions implemented by this interface and trratorAggregate (document: create an external iterator interface, and the interface returns an iterator directly.) This is similar, but it is implemented in the class definition. let's look at the example:

Class myObj implements Iterator {private $ _ data = []; public function _ construct (Array $ arr) {$ this-> _ data = $ arr;} public function current () {return current ($ this-> _ data);} public function key () {return key ($ this-> _ data);} public function next () {next ($ this-> _ data);} public function rewind () {reset ($ this-> _ data);} public function valid () {return $ this-> key ()! = NULL; }}$ t = ['yrt '=> 'Yan Ritao', 'name' => 'Yan Ritao ', false, 'yan ruitao']; $ obj = new myObj ($ t); foreach ($ obj as $ key => $ value) {echo "{$ key} => ". var_export ($ value, true ). "\ n";} // output: yrt => 'Yan Ritao 'name => 'Yan Ritao' 0 => false1 => 'Yan Ritao'

The above reference is an article by laruence about an Iterator (Iterator mode). However, the judge of laruence is a bit flawed. when the value of North is false, it will be truncated.

Introduction: PHP has several predefined interfaces, and IteratorAggregate (Iterator of aggregate Iterator) IteratorAggregate extends Traversable...

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.