简体   繁体   中英

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
 */

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM