What is the iterable type of PHP 7.1?

5

I was looking at some code to test PHP 7.1 and found the following snippet:

function doLoop(iterable $iterable) {
    foreach ($iterable as $value) {
        echo $value;
    }
}

$data = [1, 2, 3, 4];
doLoop($data);

With iterable I can make sure that the argument passed is an array , but I get the same result if I do this:

function doLoop(array $iterable) {
    foreach ($iterable as $value) {
        echo $value;
    }
}

$data = [1, 2, 3, 4];
doLoop($data);

What is the difference then in fact from array to iterable ? Is he really a type?

    
asked by anonymous 10.04.2017 / 03:15

1 answer

7

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

    
10.04.2017 / 03:36