objects..better arrays?
I was just reading through a tutorial and 开发者_如何学Cthey mentioned that Objects in php are just the better way of arrays. I am confused? Can someone clear the concept for me. thanks
That was more or less true for PHP 4, where there was no actual encapsulation. In fact, objects provide some benefits over plain array:
- Encapsulation (
private
andprotected
members) – easier to preserve invariants. - Inheritance – a type inherits the default behaviour of its superclass, you only have to replace the parts that differ.
- Dynamic dispatch (the method that's actually called depends on the type of variable) – provides decoupling of interface and implementation and abstraction.
- Less polution of global namespace with functions (less compelling since the introduction of namespaces in PHP 5.3)
I would use arrays when I have a list of the same type of data. A group of integers, a group of strings etc. Objects represent something such as a person or a car. You might say well then just use a hash array. A hash array is not very object oriented. If I'm working with an array I assume it is all related data and I can foreach, pop, shift through the data. Working with an object hopefully I know that it represents a user, car engine or computer and I can ask it questions.
精彩评论