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 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;
}
public function current() {
$var = current($this->var);
echo "current: $var
";
return $var;
}
}
$values = array(1,2,3);
$it = new MyIterator($values);
foreach ($it as $a => $b) {
print "$a: $b
";
}
Can anyone explain what is object iteration and how this code works?
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 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;
}
public function current() {
$var = current($this->var);
echo "current: $var
";
return $var;
}
}
$values = array(1,2,3);
$it = new MyIterator($values);
foreach ($it as $a => $b) {
print "$a: $b
";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Iterator 接口可能是受到 Java 迭代器的启发。它提供了一个通用接口,可以使用
foreach
结构连续迭代项目列表。您的代码定义了一个实现该接口的类。它基本上提供了与数组本身支持的功能相同的功能,但添加了一些 echo 语句。
为什么使用迭代器?
Iterator的优点是它提供了一个高级抽象接口,因此调用它的代码不需要太担心发生了什么。同时,它允许您以块的形式处理大型数据源(从数据库中获取行,从文件中读取行),而无需立即将所有内容加载到内存中。
The Iterator interface is probably inspired from the Java Iterators. It provides a generic interface to continuously iterate over a list of items using the
foreach
construct.Your code defines a class which implements this interface. It basically provides the same functionality as an array natively supports, but adds some echo statements.
Why use iterators?
The advantage of the Iterator is that it provides a high-level abstracted interface, so the code that calls it does not need to worry so much about what is going on. At the same time it allows you to process large data sources (fetching rows from a db, reading lines from a file) in chunks without having to load everything into memory at once.