PHP中的类似Java的集合 [英] Java-like Collections in PHP

查看:443
本文介绍了PHP中的类似Java的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习PHP5(上次我检查PHP是在PHP4天),我很高兴看到PHP5 OO更像Java类似于PHP4,但仍然有一个问题,使我感到不舒服,的我的Java背景:ARRAYS。

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.

我正在阅读Proffesional PHP6(Wrox),它显示了自己的集合实现。
我发现其他类似 http:// aheimlich。基于SPL的dreamhosters.com/generic-collections/Collection.phps
我还发现在SPL(ArrayObject)中有一些集合

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)

但是,我很惊讶,因为我真的没有看到人们使用在PHP中的集合,他们似乎更喜欢数组。

However, I'm surprised because I don't really see people using Collections in PHP, they seem to prefer arrays.

所以,在PHP中使用Collections是不是一个好主意,就像人们使用ArrayList而不是Java中的基本数组?毕竟,php数组并不像java数组。

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.

推荐答案

Java中的集合有很大的意义,类型语言。这是有道理的,有一个说汽车和另一个摩托车的集合。

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".

但是,在PHP中,由于动态类型的性质,牺牲集合的形式。数组足以用作各种对象类型(汽车,摩托车等)的通用容器。此外,额外的好处来自于数组可以非常容易地改变的事实(当缺少正确的错误检查时,有时可能是一个很大的缺点)。

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).

我来自一个Java背景,我发现使用PHP中的集合设计模式不会占用太多的优势(没有多线程,没有优化内存分配,没有迭代器等)。

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.

这篇关于PHP中的类似Java的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆