<?php class myIterator implements Iterator { private $position = 0 ; private $array = array( "firstelement" , "secondelement" , "lastelement" , ); public function __construct () { $this -> position = 0 ; } //第一步 function rewind () { echo ‘第一轮遍历时执行此方法 以后都不执行‘; var_dump ( __METHOD__ ); $this -> position = 0 ; } //第二步 function valid () { echo ‘valid‘; var_dump ( __METHOD__ ); return isset( $this -> array [ $this -> position ]); } //第三步 function current () { echo ‘current方法, 如果valid()方法返回false,此处停止,不往下执行‘; var_dump ( __METHOD__ ); return $this -> array [ $this -> position ]; } //第四步 function key () { echo ‘key‘; var_dump ( __METHOD__ ); return $this -> position ; } function next () { echo ‘第 ‘ . $this -> position . ‘轮遍历时执行此方法‘; var_dump ( __METHOD__ ); ++ $this -> position ; } } $it = new myIterator() ; foreach( $it as $key => $value ) { print_r($key); echo "==============>>>>>>>>>>>>>"; print_r($value); echo "\r\n \r\n"; }
时间: 2024-10-12 11:06:08