<?php class MyIterator implements Iterator { private $var = array(); public function __construct ( $array ) { if ( is_array ( $array )) { $this -> var = $array ; } } //返回到迭代器的第一个元素 public function rewind () { echo "rewinding返回到迭代器的第一个元素 " ; reset ( $this -> var ); } //返回当前元素 public function current () { $var = current ( $this -> var ); echo "current返回当前元素: $var " ; return $var ; } //返回当前元素的键 public function key () { $var = key ( $this -> var ); echo "key返回当前元素的键: $var " ; return $var ; } //向前移动到下一个元素 public function next () { $var = next ( $this -> var ); echo "next向前移动到下一个元素: $var " ; return $var ; } //检查当前位置是否有效 public function valid () { $var = $this -> current () !== false ; echo "valid检查当前位置是否有效: { $var } " ; return $var ; } } $values = array( 1 , 2 , 3 ); $it = new MyIterator ( $values ); foreach ( $it as $a => $b ) { print " $a : $b " ; } ?>