Back

I was writing out a method today that accepted an array of items as a parameter. I always try to type the array using something like: `MyObject[]`. That got me thinking about what type I should use though? Do you use `array`, `iterable`, or `Collection` if you're in the Laravel world?

2 • •

488

•
In response to @skegel

Some examples:

    /**
* @param MyObject[] myArray
*/

public function withArray(array $myArray)
{
//
}

/**
* @param MyObject[] myArray
*/

public function withIterable(iterable $myIterable)
{
// Using iterable will support both arrays or Laravel collections.
// However, you may need to use the spread operator to convert
// back to array if needed.
$array = [...$myIterable];
}

/**
* @param Collection<MyObject> myArray
*/

public function withIterable(Collection $myCollection)
{
// This gives all the power of collections which is great,
// however, it requires Laravel collections so not as useful
// outside a Laravel application.
}

2 • •

430

•
In response to @nunomaduro

In Laravel I find my self defaulting to Collection. I am spoiled 🫠

• •

146

•
  • No matching results...
  • Searching...

/ 1000