PHP 可迭代对象

创建于 2024-12-03 / 32
字体: [默认] [大] [更大]

PHP - 什么是可迭代对象?

一个可迭代对象是任何可以通过 foreach() 循环循环的值。

iterable 伪类型是 PHP 7.1 引入的,它可以作为函数参数和函数返回值的数据类型。


PHP - 使用 Iterables

iterable 关键字可以用作函数参数的数据类型或函数的返回类型:

实例

使用可迭代的函数参数:

<?php
function printIterable(iterable $myIterable) {
  foreach($myIterable as $item) {
    echo $item;
  }
}

$arr = ["a", "b", "c"];
printIterable($arr);
?> 亲自试一试 »

实例

返回一个可迭代对象:

<?php
function getIterable():iterable {
  return ["a", "b", "c"];
}

$myIterable = getIterable();
foreach($myIterable as $item) {
  echo $item;
}
?> 亲自试一试 »

PHP - 创建可迭代对象

数组

所有数组都是可迭代的,因此任何数组都可以用作需要可迭代的函数的参数。

迭代器

任何实现 Iterator 接口的对象都可以用作需要可迭代对象的函数的参数。

迭代器包含一个项目列表并提供遍历它们的方法。它保留一个指向列表中元素之一的指针。列表中的每个项目都应该有一个可用于查找项目的键。

一个迭代器必须有这些方法:

  • current() - 返回指针当前指向的元素。它可以是任何数据类型
  • key() 返回与列表中当前元素关联的键。只能是整数、浮点数、布尔值或字符串
  • next() 将指针移动到列表中的下一个元素
  • rewind() 将指针移动到列表中的第一个元素
  • valid() 如果内部指针没有指向任何元素(例如,如果 next() 在列表末尾被调用),这应该返回假。在任何其他情况下都返回 true

实例

实现 Iterator 接口并将其用作可迭代对象:

<?php
// Create an Iterator
class MyIterator implements Iterator {
  private $items = [];
  private $pointer = 0;

  public function __construct($items) {
    // array_values() makes sure that the keys are numbers
    $this->items = array_values($items);
  }

  public function current() {
    return $this->items[$this->pointer];
  }

  public function key() {
    return $this->pointer;
  }

  public function next() {
    $this->pointer++;
  }

  public function rewind() {
    $this->pointer = 0;
  }

  public function valid() {
    // count() indicates how many items are in the list
    return $this->pointer < count($this->items);
  }
}

// A function that uses iterables
function printIterable(iterable $myIterable) {
  foreach($myIterable as $item) {
    echo $item;
  }
}

// Use the iterator as an iterable
$iterator = new MyIterator(["a", "b", "c"]);
printIterable($iterator);
?> 亲自试一试 »

0 人点赞过