Java-like Collections in PHP

后端 未结 7 1342
情话喂你
情话喂你 2021-01-04 01:48

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 m

相关标签:
7条回答
  • 2021-01-04 02:46

    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.

    0 讨论(0)
提交回复
热议问题