Iterable

Iterable は PHP 7.1 で導入された疑似型です。array、あるいは Traversable インターフェイスを実装したオブジェクトを 許容します。これらの型は、いずれも foreach で繰り返し可能であり、また、 ジェネレータ 内で yield from できます。

Iterable の使用

Iterable は、関数が値のセットを要求するものの、foreach とともに使うため、 値の形式は問わないことを示すパラメータ型として使用できます。値が、配列でも Traversable のインスタンスでもない場合は、 TypeError がスローされます。

例1 Iterable パラメータ型の例

<?php

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

}

?>

Iterable として宣言されたパラメータは、null または配列をデフォルト値 として使用できます。

例2 Iterable パラメータのデフォルト値の例

<?php

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

?>

Iterable は、繰り返し可能な値を関数が返すことを示すため、戻り値の型としても 使用できます。戻り値が、配列でも Traversable の インスタンスでもない場合、TypeError がスローされます。

例3 Iterable 戻り値の例

<?php

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

?>

戻り値の型として Iterable を宣言する関数は、ジェネレータ にもなります。

例4 Iterable 戻り値のジェネレータの例

<?php

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

?>

add a note add a note

User Contributed Notes 1 note

up
-10
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