PHP Velho Oeste 2024

Iterable

Iterable は組み込みの、コンパイル時に変換される array|Traversable 型のエイリアスです。 この型は PHP 7.1.0 で導入されました。 PHP 8.2.0 より前のバージョンでは、 この型は上で述べた型のエイリアスとして振る舞う組み込みの疑似型でした。 この型は、型宣言でも使うことができます。 iterable 型は、foreach で繰り返し可能であり、 ジェネレータ 内で yield from できます。

注意:

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

例1 iterable を戻り値の型として使った、ジェネレータの例

<?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