I have a relatively simple function which uses a foreach
function foo($t) {
$result;
foreach($t as $val) {
$result = dosomething($result, $val);
}
return $result;
}
I would like to type hint, and Traversable
seems to be the exact type hint I need
function foo(Traversable $t) {
However this gives a E_RECOVERABLE_ERROR
when using an array (which is of course usable in a foreach
): example
Argument 1 passed to foo() must implement interface Traversable, array given
Is there a way to type hint or is this not possible?
The Traversable interface ¶Abstract base interface that cannot be implemented alone. Instead it must be implemented by either IteratorAggregate or Iterator. Note: Internal (built-in) classes that implement this interface can be used in a foreach construct and do not need to implement IteratorAggregate or Iterator.
PHP - What is an Iterable? An iterable is any value which can be looped through with a foreach() loop. The iterable pseudo-type was introduced in PHP 7.1, and it can be used as a data type for function arguments and function return values.
Iterable is a pseudo-type introduced in PHP 7.1. It accepts any array or object implementing the Traversable interface. Both of these types are iterable using foreach and can be used with yield from within a generator.
PHP 7.1 introduces the iterable
type declaration for this purpose, which accepts both arrays and instances of \Traversable
.
In previous versions, you'll have to omit the type declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With