Home >Backend Development >PHP Tutorial >Detailed explanation of the sample code of the Iterator pattern of the PHP class

Detailed explanation of the sample code of the Iterator pattern of the PHP class

黄舟
黄舟Original
2017-03-24 10:12:411189browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn