PHP has only a limited ability to support collections in the way that other programming languages such as C# and Java do, as far as the manner of access. This article navigates one possible solution.
To summarize, then, we can only use the Object[n] indexer notation by extending the built in ArrayObject class, but we can only implement sorting for non-primitive classes by using a custom class that knows how to work with them. The list of solutions is small and none of them are attractive:
Use a custom collection class with no indexer functionality but with full sort functionality. This means that to access an element we must explicitly make a method call.
Use an ArrayObject-derived class and create sorting methods that return a copy of the class with the elements ordered. This means that the collection class cannot sort itself.
Delightful, is it not? Personally I believe that the first solution is superior because the collection class will be able to do its own sorting. Using a Collection::Get(n) method results in extra typing, but it conveys clear intent and allows us to handle internal storage on our own. Using the second solution means we have to create either standalone functions or a sorting class for each collection class, in which we call Sort($CollectionObject). This approach is much less clear and requires a lot of additional typing, not only to use the classes but also to modify them or create new ones - and of course it requires that we remember more class names, more method names, and how to use them all in conjunction with one another.
Having determined that the first solution is better, this article will focus on implementing that solution in a clean and manageable way. Read on!