|
Posted by Rob on 01/22/08 13:06
On Jan 21, 6:07 pm, co...@nospmanthanks.com wrote:
> I understand what a class is but am confused as to why so many people are
> using them for what appear to be very simple PHP applications. I guess I
> dont know enough about how they are useful.
>
> for example I've just seen a "who is" application thats just 2 files
> and a few dozen lines of very simple code
>
> But the author put the thing into a class. This just seems to complicate
> the code without providing any benefits as far as I can see.
>
> Can someone explain what the advantage of this is please? And any advice
> on when or when not to use classes would be helpful?
>
> cheers
>
> Col.
Jerry - what you've described could also be a function as well, not
that I'm trying to belittle you.
This is what I wrote when asked the same question, although it was
actually describing JavaScript classes :-
"A class is just a way of describing what something looks like and how
it works, like a template.
For instance, suppose we had a class called 'Car'. We can create an
'instance' of the class called 'VW Beetle'. Our new copy of 'Car' has
all the things the 'Car' class has, such as wheels, mirrors, doors,
etc - these are called 'Properties' It also has actions, such as
drive, park, reverse, etc - these are called 'Methods'.
We can use the 'Car' template to create as many copies as we want
(using the 'new' keyword). Each copy is known as an 'Object', and
although it has all the features of the class, it is a unique
instance."
In addition to this, one of the most powerful features of a class is
it's inheritance, which you can't do with a function.
Suppose we have a class called 'Vehicle'. We could say it has certain
properties, such as wheels, colour, size, etc. With this base class,
we can also create a whole new class, called 'Car' that inherits all
of the features of the 'Vehicle' class.
We can also add specific 'Car' methods and properties to our new
class, such as engine, ignition, gears, etc. We can also overwrite the
methods of a base class, so instead of the 'ChangeGear()' method of
our Vehicle class effecting just the gears, we could get it to change
the gear and display the current gear on the dashboard.
Obviously Vehicles and Cars is not a real world example, but it gives
you some point of reference about how the models work together, and is
only one good use of classes.
I do agree with you that this can all turn into spaghetti code, but if
used correctly, becomes immensely powerful.
Rob.
[Back to original message]
|