What is the iterable type of PHP 7.1 for?

Asked

Viewed 178 times

5

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

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

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

With the iterable I can ensure that the past argument is a array, but I can achieve 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 of the array to the iterable? He really is a guy?

1 answer

7


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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.