Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Traversable type hint

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?

like image 226
dtech Avatar asked Jun 10 '13 19:06

dtech


People also ask

What is traversable PHP?

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.

What is Iterables in PHP?

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.

What is Iterable type?

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.


1 Answers

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.

like image 199
Andrea Avatar answered Sep 27 '22 19:09

Andrea