Java-like Collections in PHP

I am very pro collection objects in PHP, they can be used to add type safety, impliment easy to use search, sort and manipulation functionality, and represent the correct OO approach rather then using arrays and the multitude of useful but procedual functions that operate on them in differing patterns all over the source.

We have various collections that we use for various purposes all neatly inherited promoting type safety, consistent coding standards and a high level of code reuse.

But ultimatley, they are all array's internally!

I suppose really it comes down to choice, but in my object oriented world I like to keep easily repeatable segments of code such as sort and search algorithms in base classes, and I find the object notation more self documenting.


PHP arrays are associative... They're far more powerful than Java's arrays, and include much of the functionality of List<> and Map<>.

What do you mean by "good idea"? They're different tools, using one language in the way you used another usually results in frustration.


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.