Forum Moderators: coopster

Message Too Old, No Replies

Arrays Versus Objects

Any real advantage or just preference

         

Mr_Fern

7:56 pm on Jul 26, 2005 (gmt 0)

10+ Year Member



I've been working with PHP approximately 2 and a half years now. Over that time span I made a few basic scripts for my personal site and recently as of late a more extensive project.

I was just curious if there's any real advantage in using objects to store some data over arrays. Most of my database calls fetch row data in arrays, some in objects. I don't have a real reason for the mixing of fetching rows as arrays and as objects as well.

Anywho I was curious if there was any real advantage to using objects over arrays, either in execution time or time to write program, or something else I'm not thinking of. Or is it really more of just a programmer preference thing?

ergophobe

5:58 pm on Jul 27, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



There are three advantages to objects

1. Object can have both properties (similar to array elements) and methods (similar to functions).

2. One class serves as a definition for any number of objects and can initialize values to defaults and so on. Arrays have to be defined for each instance of a similar array.

3. And now the real meat of it... You can control access to different parts of the object. This is *not* true in PHP4 and much of the utility of objects is lost in that case. In PHP 5 and most object-oriented languages, you can define a public interface and private variables and methods. So for example (in pseudocode, not any particular language)


class myclass
{
private
priv_property;
priv_method();
public
pub_property;
pub_method();
}

Now, all functions that are class members can access both the public and private properties and methods. From outside the class, though, only the public properties and methods are available.

Some programmers go so far as to say that no properties should be public, but only "getProperty()" and "setProperty()" methods. Why would anyone say this? Because, by doing that, I can check that the data type is the correct type every time it gets assigned if necessary. Or, I can make the getProperty public by not the setProperty.

In short, it allows me to protect my data and functions and make the object a sort of blackbox that nobody can interfere with from the outside world.

Why would I want to do that? Because, that means that all I have to maintain from one version to the next is the interface. The implementation is irrelevant except within the class. This is especially important for reusing code and collaborating with others.

As I said, PHP4 isn't up to the task in this respect, but with PHP5 you'll start to see some of the real advantages of objects.