Iterable and Callable Types

Posted on Updated on PHP by Gergő D. Nagy

If we dig deeper into the core code of Laravel, we can see various types that are not that common, for example, iterable and callable. Now let’s take a look at those and see what are they exactly.

Iterable

The iterable pseudo-type was introduced in PHP 7.1. An iterable value can be an array or an object that implements the `Traversable` interface. It means, foreach can be used on both types and their values can be used with yield inside of a generator instance.

Iterable is a dynamic type. Using the Traversable interface, any object can be “converted” to iterable.

/**
 * Loop through on the iterable item.
 *
 * @param iterable $data
 * @return iterable
 */
function each(iterable $data): iterable {
    foreach ($data as $value) {
        //
    }
    return $data;
}

Callable

The hint `callable` is also another type that can be various things. It can be a callback, a named function, object method – even static class methods as well. It’s important to see, callable is different from Closure.

/**
 * Loop through on the iterable item and fire the given callback.
 *
 * @param iterable $data
 * @param callable $callback
 * @return callable
 */
function each(iterable $data, callable $callback): iterable {
    foreach ($data as $value) {
        $callback($value);
    }

    return $data;
}

Summary

Small pieces of information – and making small experiments – can help quite much to understand more and more about how things work. For example, Laravel is using a lot of these types to keep things in a good flow, yet keep control over the consistency. It’s nice to dig a bit deeper, read the docs to have a bit more light in the room.

Need a web developer? Maybe we can help, get in touch!