PHP 可迭代对象
PHP - 什么是可迭代对象?
可迭代对象是任何可以用 `foreach()` 循环遍历的值。
PHP 7.1 中引入了 `iterable` 伪类型,它可以作为函数参数和函数返回值的类型。
PHP - 使用可迭代对象
`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()`),则应返回 false。在任何其他情况下都返回 true。
示例
实现 Iterator 接口并将其用作可迭代对象
<?php
// 创建一个迭代器
class MyIterator implements Iterator {
private $items = [];
private $pointer = 0;
public function __construct($items) {
// array_values() 确保键是数字
$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() 指示列表中有多少项
return $this->pointer < count($this->items);
}
}
// 使用可迭代对象的函数
function printIterable(iterable $myIterable) {
foreach($myIterable as $item) {
echo $item;
}
}
// 将迭代器用作可迭代对象
$iterator = new MyIterator(["a", "b", "c"]);
printIterable($iterator);
?>
自己动手试一试 »