Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java-like Collections in PHP

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.

like image 585
ivmos Avatar asked Oct 16 '09 20:10

ivmos


People also ask

Does PHP have Collections?

The Collection interface ¶Collection is the base interface which covers functionality common to all the data structures in this library. It guarantees that all structures are traversable, countable, and can be converted to json using json_encode().

What is the difference between collection and array in PHP?

2. Collection vs Array Array is just the normal array, whereas a PropelCollection is an Object of Objects, which has a lot of stuff available such as: Paging results.


1 Answers

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.

like image 185
Pras Avatar answered Oct 21 '22 08:10

Pras