He’s not a guy, he’s a pseudo guy (just like callable
). Its function is to indicate that the function accepts as a parameter both array
as any object implementing the interface Traversable
. That is, it also accepts objects of the type array-like, functioning on a loop foreach
.
If specified in a function parameter, it will accept values of type array
, Iterator
, Generator
, etc. If it is none of these types, an exception of type TypeError
is fired.
function foo(iterable $iterable) {
foreach ($iterable as $value) {
// ...
}
}
Can also be used to set the return of a function:
function bar(): iterable {
return [1, 2, 3];
}
When used in parameters, it may have default value null
or even a array
emptiness.
function foo(iterable $iterable = null) {
// ...
}
And how the generator
is a sub-type of Traversable
, the following is valid:
function gen(): iterable {
yield 1;
yield 2;
yield 3;
}
Basically, to find out if it’s a possible type of iterable
, just use the function is_iterable
:
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 reserved word for class names, so classes, interfaces and traits cannot be named as iterable
.
Note: however much PHP allows you to use foreach
on objects, iterating on the public properties of it, the object will not be considered iterable
if you’re not the type Traversable
.
Reference: PHP RFC: Iterable