軟件環境
php 7.1.33 + windows 10 操作系統
代碼示例
<?php
class MyIterator implements Iterator
{
private $_myArr = [
'a' => 1024,
128,
'c' => 8421,
256
];
/**
* 當前元素的值
*
* @return mixed
*/
public function current()
{
return current($this->_myArr);
}
/**
* 移動指針指向下一個元素
*/
public function next()
{
next($this->_myArr);
}
/**
* 當前元素的鍵名
*
* @return mixed
*/
public function key()
{
return key($this->_myArr);
}
/**
* 當前元素是否存在
*
* @return bool
*/
public function valid()
{
return $this->current() !== false;
}
/**
* 移動指針指向第一個元素(復位)
*/
public function rewind()
{
reset($this->_myArr);
}
}
$obj = new MyIterator();
foreach ($obj as $key => $value) {
echo "{$key} => {$value}\n";
}