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
*/
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.
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, ...) { // ... }
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.
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) { /*...*/ }
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