PHP predefined interfaces

Source: Internet
Author: User
Tags rewind
This article mainly sorts out the predefined interfaces of PHP, which are commonly used in the project process: IteratorAggregate (Iterator of aggregate Iterator), Countable, ArrayAccess, Iterator, you can refer to the following predefined interfaces in PHP, which are commonly used ( IteratorAggregate (aggregate Iterator), Countable, ArrayAccess, Iterator.

IteratorAggregate (aggregate Iterator) interface


The code is as follows:


IteratorAggregate extends Traversable {
Abstract public Traversable getIterator (void)
}

This interface implements a function-create an external iterator. how can this problem be solved?ForeachIf the object is not inheritedIteratorAggregateInterface that traverses all the public attributes of an object (only in the form of public $ var ). If it inheritsIteratorAggregateWill useGetIteratorThe object returned by the method.TraversableObject or extended fromTraversableObject. 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 => LULU

Countable interface

The code is as follows:


Countable {
Abstract public int count (void)
}

This interface is used to count the number of objects. how can we understand it? when we call an objectCountIf the function does not inheritCountableWill always return 1, if inheritedCountableWill return the implementedCountThe number returned by the method. See 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); // return 3ArrayAccess interface ArrayAccess {abstract public boolean offsetExists (mixed $ offset) abstract public mixed offsetGet (mixed $ offset) public void offsetSet (mixed $ offset, mixed $ value) public void offsetUnset (mixed $ offset)} class CountMe {protected $ _ myCount = 3; public function count () {return $ this-> _ myCount; }}$ countable = new CountMe (); echo count ($ countable ); // return 1 class CountMe implements Countable {protected $ _ myCount = 3; public function count () {return $ this-> _ myCount ;}}$ countable = new CountMe (); echo count ($ countable); // returns 3

ArrayAccess interface

The code is as follows:


ArrayAccess {
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 the Notice

The above object can only be a basic array operation, even the traversal is not good, combined with the previousIteratorAggregateAvailableForeach:

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

Iterator interface:


The code is as follows:


Iterator 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 andTrratorAggregate(Document: create an external iterator interface, and the interface returns an iterator directly.) This is similar, but it is implemented by yourself in the class definition. See the example below:

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.


Summary
After talking about this, it seems that they still haven't realized their usefulness. we suggest you look at the source code of Yii2. the source code uses a lot of these things. after reading this, you will slowly feel "oh ~ It seems very useful ...."

I hope you will like this article.

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.