Iterable 可迭代对象

Iterable是 PHP 7.1 中引入的一个伪类型。它接受任何 array 或实现了 Traversable 接口的对象。这些类型都能用 foreach 迭代, 也可以和 生成器 里的 yield from 一起使用。

使用可迭代对象

可迭代对象可以用作参数类型,表示函数需要一组值, 但是不会关心值集的形式,因为它将与 foreach 一起使用。如果一个值不是数组或 Traversable 的实例,则会抛出一个 TypeError

示例 #1 Iterable 可迭代参数类型示例

<?php

function foo(iterable $iterable) {
    foreach (
$iterable as $value) {
        
// ...
    

}

?>

声明为可迭代的参数可能会使用 null 或者一个数组作为默认值。

示例 #2 可迭代参数默认值示例

<?php

function foo(iterable $iterable = []) {
    
// ...
}

?>

可迭代对象还可以用作返回类型,表示函数将返回一个可迭代的值。 如果返回值不是数组或 Traversable 的实例,则会抛出一个 TypeError

示例 #3 可迭代返回类型示例

<?php

function bar(): iterable {
    return [
123];
}

?>

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

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

<?php

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

?>
add a noteadd a note

User Contributed Notes 1 note

up
-51
j_jaberi at yahoo dot com
2 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.

备份地址:http://www.lvesu.com/blog/php/language.types.iterable.php