Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Type hint for Laravel Collection or Array

I would like to create a function which accepts any traversable object as parameter, for example Laravel Collection/Array. Is there any way to type hint this condition in the function parameter??

I want the effect of both the following in single definition:

function test(array $traversable)
{
    print_r($traversable);
}

AND

function test(Illuminate\Support\Collection $traversable)
{
    print_r($traversable);
}

AND the DocBlock should be

/**
 * Function to do something
 * 
 * @param Collection|Array $traversable Traversable parameter
 * @return null Absolutely nothing
 */
like image 900
B.A.B Avatar asked Sep 09 '16 07:09

B.A.B


People also ask

What is type hint in laravel?

In simple word, type hinting means providing hints to function to only accept the given data type. In technical word we can say that Type Hinting is method by which we can force function to accept the desired data type. In PHP, we can use type hinting for Object, Array and callable data type.

Which is the right way to type hint a function PHP?

To add a type hint to a parameter, you place a type in front of it like this: <? php function my_function(type $param1, type param2, ...) { // ... }

Which method breaks the Collection in laravel?

Laravel 5 Collections: Breaking a Collection Into a Specified Number of Groups With split. The split method is similar to the chunk method in that it used to break a collection into a smaller number of collections.


1 Answers

PHP 7.1 will introduce the iterable typehint which will do exactly that:

function test(iterable $items) { /*...*/ }

See PHP - rfc:iterable.

Until then you can't use any typehint if you want to accept both Traversable and array. The only thing you can do is use a proper @param annotation to document it:

/**
 * @param \Traversable|array $items
 */
function test($items) { /*...*/ }
like image 138
ShiraNai7 Avatar answered Sep 17 '22 18:09

ShiraNai7