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?
Back
•
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.
}
•
good question; i typically just use array, and specify the array shape using the generic syntax: array<int, something>.
•
In response to @nunomaduro
In Laravel I find my self defaulting to Collection. I am spoiled ðŸ«