Java-like Collections in PHP

ivmos picture ivmos · Oct 16, 2009 · Viewed 18.9k times · Source

I'm learning PHP5 (last time I checked PHP was in PHP4 days) and I'm glad to see that PHP5 OO is more Java-alike than the PHP4 one but there's still an issue that makes me feel quite unconfortable because of my Java background : ARRAYS.

I'm reading "Proffesional PHP6" (Wrox) and It shows its own Collection implementation. I've found other clases like the one in http://aheimlich.dreamhosters.com/generic-collections/Collection.phps based on SPL. I've also found that there's some kind of Collection in SPL (ArrayObject)

However, I'm surprised because I don't really see people using Collections in PHP, they seem to prefer arrays.

So, isn't it a good idea using Collections in PHP just like people use ArrayList instead of basic arrays in Java? After all, php arrays aren't really like java arrays.

Answer

Pras picture Pras · Oct 16, 2009

Collections in Java make a lot of sense since it's a strongly typed language. It makes sense to have a collection of say "Cars" and another of "Motorbikes".

However, in PHP, due to the dynamically typed nature, it is quite common to sacrifice the formality of Collections. Arrays are sufficient to be used as generic containers of various object types (Cars, Motorbikes, etc.). Also, the added benefit comes from the fact that arrays can be mutated very easily (which sometimes can be a big disadvantage when proper error checking is absent).

I come from a Java background, and I've found that using a Collections design pattern in PHP does not buy much in the way of advantages (no multi-threading, no optimization of memory allocation, no iterators, etc.).

If you're looking for any of those advantages, its probably better to construct a wrapper class around the array, implementing each feature (iterators, etc.) a la carte.