<bi******@yahoo.co.uk> wrote in message
news:11*********************@c13g2000cwb.googlegro ups.com...
Hi there,
I have been using PHP for a few years but never used classes. I
understand how they are created and how they work but was unsure about
when you use them.
Any help? Cheers
Burnsy
Well, if you haven't use classes then you probably don't need them for what
you're doing. Usually it's self-evident when using a class is appropriate.
In the case of basic web application development in PHP, there aren't that
many instances where it brings much benefit.
Objects are good for managing states. For example, I like to use objects to
hold data coming from the database. Fields are exposed as object properties
which my application code can freely get and set. Each object internally
keeps copies of the original values, so that when it comes time to save the
data back to the database I can easily tell which fields have changed and
which have not.
A crude example:
class User {
var $user_id;
var $user_name;
var $first_name;
var $last_name;
var $org_user_name;
var $org_first_name;
var $org_last_name;
function User($row = false) {
if($row) {
$this->user_id = $row['user_pk'];
$this->first_name = $this->org_first_name = $row['first_name']
// ... and so on
}
}
function Save() {
if(!$this->user_id) {
// no primary key, meaning we need to do an insert
}
else {
if($this->first_name != $this->org_first_name) {
// add to update list
}
// ... and so on
}
}
}
Situations where a PHP script need to remember state information don't
happen very often though. Most of the time things are calculated, echo'ed to
the client, and quickly discarded. Simple functions serve you well enough.