Iterable 可迭代对象

Iterable 是内置编译时 array|Traversable 的类型别名。从 PHP 7.1.0 到 PHP 8.2.0 之间的描述来看,iterable 是内置伪类型,充当上述类型别名,也可以用于类型声明。iterable 类型可用于 foreach 或在生成器中使用 yield from

注意:

将可迭代对象声明为返回类型的函数也可能是 生成器

示例 #1 可迭代生成器返回类型的示例

<?php

function gen(): iterable {
yield
1;
yield
2;
yield
3;
}

?>

add a note add a note

User Contributed Notes 1 note

up
-13
j_jaberi at yahoo dot com
4 years ago
Just to note:
Though objects may (or may not) be Traversable, the can use in foreach because implicit conversion to array
<?php
class Foo {
    public
$a = 1;
    public
$b = "Helo";
};

$bar = new Foo;

foreach(
$bar as $elm) {
    echo
$elm . ' ';
}

?>
prints 1 Hello
Even
<?php
$bar
= new stdClass
foreach($bar as $elm) {
    echo
$elm . ' ';
}
?>
is correct.
To Top