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);
?>
自己動手試一試 »