loading...

Collection objects in PHP

Vincent Fahrenholz on September 14, 2018

The problem with arrays In PHP arrays are a very flexible data structure, which accepts almost everything and can be combined any way you like. ... [Read Full]
markdown guide
 

Guys. Maybe don't do that? Use strict typing and the splat/spread operator, as shown here, so you can add or more values, and you get type checking exceptions for free:
medium.com/2dotstwice-connecting-t...

 

As you mentioned arrays are very flexible and offer freedom for developers. It's what makes them good but also very annoying to consume. Personally i feel that only arrays containing a single type is acceptable as return value (see my post on the subject). Iterators are better in most cases.

To be honest i really don't think it's important to implement ArrayAccess on collections (or extend ArrayObject). It's not really bad... but somehow using that bracket syntax feels awkward.

Lack of collections is a pain in the ass in PHP. There is really no convenient way to achieve type safety for collections at the moment (at least one i know of). I create collections all the time by just implementing IteratorAggregate but this means that i do have to create a new class each time i want type safety for a collection.

I really hope we'll see generics sooner rather than later. Also sets and maps.

 

I've also seen a work in progress around built-ins collections : php.net/manual/fr/class.ds-collect..., might be the next step over Sets, Maps and others useful collections like the one Python provide.

 

I've seen it also, but it is a pecl extension (working with PHP 7). I doubt it will become core soon.

 

Too bad, I feel PHP diserve those built-ins, kind of like they are doing for strictly typed variables...

 

Guys, check out a collection package I have been working on since may 2018

github.com/rotexsoft/versatile-col...

It is fully documented and it supports strict typing. It has a lot of the laravel collection features and more.

Cheers!

code of conduct - report abuse