Home > Article > Backend Development > Detailed explanation of the sample code of the Iterator pattern of the PHP class
This is about PHP’s built-in interface Iterator. PHP5 begins to support interfaces, and has a built-in Iterator interface, so if you define A class and implements the Iterator interface, then your classobject is ZEND_ITER_OBJECT, otherwise it is ZEND_ITER_PLAIN_OBJECT.
For the ZEND_ITER_PLAIN_OBJECT class, foreach will obtain the default value of the object through HASH_OFAttributeArray, and then perform foreach on the array.
For the ZEND_ITER_OBJECT class object, the foreach will be performed by calling the Iterator interface related functions implemented by the object, so, for this For written test questions, you can give the following answers:
<?php class sample implements Iterator { private $_items = array(1,2,3,4,5,6,7); public 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; } ?>
The above is the detailed content of Detailed explanation of the sample code of the Iterator pattern of the PHP class. For more information, please follow other related articles on the PHP Chinese website!