17

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.

dreftymac
  • 31,404
  • 26
  • 119
  • 182
cort
  • 1,088
  • 1
  • 11
  • 20

7 Answers7

19

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.

Mark Fox
  • 8,694
  • 9
  • 53
  • 75
Pras
  • 1,435
  • 1
  • 11
  • 13
  • 1
    Constructing my own wrapper class has the disadvantage of using a non standart class for such a basic thing. Is SPL's ArrayObject a wrapper? – cort Oct 16 '09 at 20:46
  • 1
    Agreed, any custom wrappers have the disadvantage of being non-standard, but that may not be so bad since there really isn't a standard Collections wrapper. I haven't really worked with SPL's ArrayObject, but looking at the docs (http://www.php.net/~helly/php/ext/spl/classArrayObject.html), it seems to be a wrapper class that adds a clone function and iterators. If this is all you ever need, I'd recommend using it. But if you need synchronization, linkedlist vs. arraylist, etc. you'll probably need to either write your own wrapper or extend ArrayObject. – Pras Oct 16 '09 at 21:04
  • Totally agree, but sometime you just want to have a basic assurance that an array contains only one type of object. I have a simple implementation that I use - see my answer below – GWed Jun 19 '15 at 12:16
6

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.

Gavin
  • 2,153
  • 2
  • 25
  • 35
5

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.

Nick Veys
  • 23,458
  • 4
  • 47
  • 64
  • There're a lot of OO design patterns which are being used in PHP and the PHP5 OO is really Java-alike so using some kind of Collection seemed a good idea to me. – cort Oct 16 '09 at 20:43
  • 2
    The fact that PHP borrowed some things from Java is not necessarily a good thing. – Ionuț G. Stan Oct 17 '09 at 00:44
  • I guess I'm confused. You _do_ have "collections". They're just not named "List" or "Map". The PHP arrays will grow dynamically. You can associate key/value pairs. Sets are a little different beast, but hey, can't pile too much in there. :) Coming from Java it's certainly a strange world out there, but embrace these differences and the tradeoffs that come with them! – Nick Veys Oct 17 '09 at 03:22
3

I, too, was somewhat dismayed to find no Collection type classes in PHP. Arrays have a couple of real disadvantages in my experience.

First, the number of functions available to manipulate them is somewhat limited. For example, I need to be able to arbitrarily insert and remove items to/from a Collection at a given index position. Doing that with the built-in language functions for arrays in PHP is painful at best.

Second, as a sort of offshoot of the first point, writing clean, readable code that manipulates arrays at any level of complexity beyond simple push/pop and iterator stuff is difficult at best. I often find that I have to use one array to index and keep track of another array in data-intensive apps I create.

I prefer working in a framework (my personal choice is NOLOH). There, I have a real Collection class called ArrayList that has functions such as Add, Insert, RemoveAt, RemoveRange and Toggle. I imagine other PHP frameworks address this issue as well.

Dan Shafer
  • 61
  • 1
  • 6
0

A nice implementation of collection in php is provided by Varien Lib, this library is part of Magento code with OSL license. ( more info about Magento license and code reuse here.

Cannot find any source code for the library so the best way is to download magento and then look in /lib/Varien/

Community
  • 1
  • 1
WonderLand
  • 5,494
  • 7
  • 57
  • 76
0

Yii has implementation of full java like collections stack

http://www.yiiframework.com/doc/api/1.1/CList

Sumit Kumar
  • 1,855
  • 19
  • 19
0

I sometimes use this really simple implementation to give me a rough and ready collection.

Normally the main requirement of a collection is enforcing a group of one type of object, you just have to setup a basic class with a constructor to implement it.

class SomeObjectCollection {

   /**
    * @var SomeObject[]
    */
   private $collection = array();

   /** 
    * @param SomeObject $object1
    * @param SomeObject $_ [optional]
    */
   function __construct(SomeObject $object1 = null, SomeObject $_ = null) 
   {
       foreach (func_get_args() as $index => $arg) {
           if(! $arg instanceof SomeObject) throw new \RuntimeException('All arguments must be of type SomeObject');
           $this->collection[] = $arg;
       }
   }

   /**
    * @return SomeObject[]
    */
   public function getAll()
   {
       return $this->collection;
   }
}
GWed
  • 15,167
  • 5
  • 62
  • 99