php中的对象迭代是什么

发布于 2024-10-22 20:57:17 字数 949 浏览 5 评论 0原文

谁能解释什么是对象迭代以及这段代码是如何工作的?


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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

早乙女 2024-10-29 20:57:17

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文