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

490

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

432

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

/ 1000

good question; i typically just use array, and specify the array shape using the generic syntax: array<int, something>.

1

764

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

148

What we are doing here is providing some data to a class so the class can work with this data. If my return type states this part is an array, we are asking: will my function always take in an array of data?

This means we need to consider what an array is. An array is an iterable object that is, in PHP, basically a hashmap: a key-value store. These are so-called data structures and help us organize data. An iterable in PHP is much more than just an array; it does not exist and is a pseudo-type. Linked lists are an implementation of iterables, as are stacks, collections, queues, and generators.

So this is what you are essentially asking:

Will I change the way I manage my data?

Ironically, we do this a lot in Laravel. So if you're working on a large project, it's quite a good idea.

If this is something you're planning to do, make sure you think of the inserted data as an iterable implementation and don't use specific functions for arrays, collections, or any other data structure.

1

152

Good point, I will give it a shot and consider it

I've been all in with Collections since I read Adam Wathan's "Refactoring to Collections" (adamwathan.me/refactoring-to-collections

). But this is a good chance to step back, reflect and rethink some default choices I have engrained when implementing solutions instead of considering what is best for the job at hand.

Thanks!

132