It is not a type, it is a pseudo type (such as callable
). Its function is to indicate that the function accepts as parameter both array
and any object that implements the Traversable
interface. That is, it also accepts array-like objects, which work in a loop foreach
.
If indicated in the parameter of a function, it will accept values of type array
, Iterator
, Generator
, etc. If it is not any of these types, an exception of type TypeError
is thrown.
function foo(iterable $iterable) {
foreach ($iterable as $value) {
// ...
}
}
It can also be used to define the return of a function:
function bar(): iterable {
return [1, 2, 3];
}
When used in parameters, it may have default value null
or even array
empty.
function foo(iterable $iterable = null) {
// ...
}
And since generator
is a subtype of Traversable
, the following is valid:
function gen(): iterable {
yield 1;
yield 2;
yield 3;
}
Basically, to know if it's a possible type of iterable
, just use the is_iterable
function:
var_dump(is_iterable([1, 2, 3])); // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(is_iterable((function () { yield 1; })())); // bool(true)
var_dump(is_iterable(1)); // bool(false)
var_dump(is_iterable(new stdClass())); // bool(false)
The word iterable
is defined as a keyword reserved for class names, so classes, interfaces, and traits can not be named as iterable
.
Note : Although PHP allows you to use foreach
on objects, iterating over public properties of it, the object will not be considered iterable
if it is not of type Traversable
.
Reference : PHP RFC: Iterable