why use a class

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hi Folk

I was wondering to hear from you why you use classes in some instances  
rather than functions.  I have never used a class, but I use a lot of  

I don't have a comp sci background, so I may miss some of the basics.


- Nicolaas  

Re: why use a class

A class is really more analogous to a structure than to a function.

A class is like a structure but it can 'inherit' from another class,
and it can have functions (aka methods) that are members of the class.


OS X 10.4  

G5 Dual 2GHZ / 160GB / 1GB RAM / Superdrive
Apple 20" Cinema Display
SmartDrive 120GB Firewire HD
Maxtor 250GB SATA

Visit my wife's eBay store !!


Not thrilled about the Intel switch, but trying to remain optimistic.
brianleahy's Profile: http://www.macosx.com/forums/member.php?userid=456
View this thread: http://www.macosx.com/forums/showthread.php?t=237525
macosx.com - The Answer to Mac Support - http://www.macosx.com

Re: why use a class

Following on from windandwaves's message. . .
Quoted text here. Click to load it
I know where you're coming from.

Look on classes and OO as a good way to do lots of things.  You'll still  
use 'stand alone' functions but _thinking about_ things in an OO way  
should make a big difference.  Just like your function library took time  
to develop so will your collection of handy objects.

For example I have database and table classes to replace my collection  
of database related functions. A lot of the code is the same, but one of  
the things I can do now is prepare and cache certain things to assist  

There are plenty of easy examples. See chapter 14 of the PHP manual.  An  
excellent example is creating an email.  There are a number of classes  
around which basically let you set a load of elements then do the dirty  
work for you.

One example is having a user class (and working with instance objects).  
[You can think of _class_ as being the ideas that make it work, the  
design and interrelationships with other objects, and the _object_ as  
the practical realisation which gets processed.]  My standard user class  
handles creating a new user, interfacing with a database table, managing  
passwords, managing permissions and change of email address etc.  At the  
top of every page I can do /something/ like

$cu = GetCurrentUser();   // this is a stand alone function
$cu.CheckPermissions('IsAdmin');  // this is an object-function

The thing is I know that all my user related data and procedures are in  
the one place and the messy bits are nicely wrapped up.  If experience  
shows that the user class could usefully be enriched then I only have to  
visit one bit of code to do it knowing that the behaviour will not be  
adversely affected by no-longer applicable functions.  For example there  
is a class-function to validate a password then I thought it would be  
great to allow another developer to plug-in their own function.  Not a  
single bit of page code had to be changed to make use of this feature,  
it was all handled 'inside' the class.

There are other good reasons for adding the ability to write and use  
classes to your repertoire but it is too large a subject to go into  

PETER FOX Not the same since the bolt company screwed up
2 Tees Close, Witham, Essex.
Gravity beer in Essex  <http://www.eminent.demon.co.uk

Re: why use a class

Peter Fox wrote:
Quoted text here. Click to load it

Hi Peter

Thank you for your in-depth answer. I am just trying to wrap my head around  
it ;-)

In VB it was really nice (paradox?) when I created a class that when I  
typed, for example, "myclass." then it would show all the methods for the  
class (i.e.the autocomplete).  However, in PHP I work in Notepad2, which  
does not have that function (well, as far as I know).

Now, I have a function in a file called dropdown.php.  It creates a dropdown  
for any given table and field:

//creates a dropdown for a table
//$table = the name of the table
//$name = the name of the select control
//$class = the class of the select control
//$select = the ID of the item that should be selected as default
//$fieldname = the name of the field in the table that should be shown
//requires the primary key in the table to be named as ID

function dd($table, $name, $class, $select, $fieldname){
 $sql = 'SELECT `ID`, `'.$fieldname.'` FROM `'.$table.'` '.$sqlw.' ORDER BY  
 $query = mysql_query($sql);
 $v = '<select name="'.$name.'" id="'.$name.'" class="'.$class.'">';
 while ( $row = mysql_fetch_row($query) ) {
  $v .= '<option';
  if ( $select && $row[0] == $select ) {
   $v .= ' SELECTED ';
  $v .= ' VALUE="'.$row[0].'">'.$row[1].'</OPTION>';
 $v .= "</SELECT>";
 return $v;

dont worry about the code, I am sure you get the gist.  How would this  
function benefit from being put into a class?  I am not doubting that this  
would be useful, I just trying to understand the concept better.

Thank you again for your great answer...  It made it such much clearer.  

Re: why use a class

windandwaves wrote:

Here is another bunch of functions that I think may benefit from being in a  
class, but I am not sure how...
The file is called mysql.php and it is part of my library.


//this file provides basic sql functions that are used by other scripts
//you have to be careful with SQL because it can screw with your data
//therefore, never use " quotes but always use ' to encapsulate queries
//also, encapsulate fields and tables with ` symbols
//actual values (e.g. `ID` = "3") to be inserted should be encapsulated with  
"-style quotes
//it does not make much difference, but it definitely protects against basic  
SQL injection.

//used for action queries (delete, insert, update)
function sqler($s) {
 $query = mysql_query($s);
  return 1;
 else {
  sqllog("error in previous entry");
  return 0;


//allows you to select the first field of the first row in a query (can have  
only one row)
//e.g. $s = select d from final where id =1;
function mysql_zz($s) {
 $query = mysql_query($s);
 if($query) {
  if (mysql_num_rows($query) != 1) {
   sqllog("error in previous entry");
   return false;
  return mysql_result($query, 0,0);
 else {
  sqllog("error in previous entry");

//return value in table (t) for field (f) where (id)
function look($t, $f, $id) {
 return mysql_zz('SELECT `'.$t.'`.`'.$f.'` FROM `'.$t.'` WHERE ID =  

//like look but returns a string if the record can not be found
function lookd($t, $f, $id) {
 $v = look($t, $f, $id);
 if ( $v ) {
  return $v;
 else {
  return 'record not defined';

//looks up the value for a certain table where a certain field is a certain  
function idlook($t, $f, $v) {
 return mysql_zz('SELECT `'.$t.'`.`ID` FROM `'.$t.'` WHERE '.$f.' =  

function tcount ($t, $w) {
 return mysql_zz('SELECT (COUNT(`'.$t.'`.`ID`)) a FROM `'.$t.'` WHERE '.$w.'  

//checks if ID exists and makes sure no sql is injected, mainly useful for  
autonumber IDs
function idok($t, $id) {
 $min = maxi($t, true);
 $max = maxi($t, false);
 $id = sanitize_int($id, $min, $max);
 if($id) {
  return mysql_zz('SELECT `'.$t.'`.`ID` FROM `'.$t.'` WHERE ID =  
 else {
  return 0;

//check if ID exists for short lookup lists
function idok_byte($t, $id) {
 $id = sanitize_int($id, 0, 255);
 return mysql_zz('SELECT `'.$t.'`.`ID` FROM `'.$t.'` WHERE ID =  

//finds the max and/or min ID-value for a certain table
function maxi($t, $min = false){
 if ($min) {
  $word = 'MIN';
 else {
  $word = 'MAX';
 return mysql_zz('SELECT '.$word.'(ID) FROM `'.$t.'`;');

function sqllog ($s) {
 $sql = 'INSERT INTO `SQL` ( `MEM` ) VALUES ("'.removequotes($s).'");';
 return mysql_query($sql);


Re: why use a class

Following on from windandwaves's message. . .
Quoted text here. Click to load it

What would you say to someone who said: "I think I might benefit from  
changing my car into a motorbike"?  Probably something like "you're  
looking at it the wrong way." Then perhaps (a) Learn what a motorbike is  
good for (b) Learn how to ride it (c) Use whichever mode of transport  
suits whatever you happen to want to do at the time.

If a genie jumped out of a lamp and said "Thou must go on a long and  
dangerous quest" then popped back into his lamp without further  
information would you pack your bags and head off in any direction not  
knowing what you were looking for?  - Probably not.

The bottom line is you have to study the OO subject a bit more by  
reading the basic principles and theory (a little), reading the manual  
(doesn't take long) and experimenting (a bit).


PETER FOX Not the same since the bra business went bust
2 Tees Close, Witham, Essex.
Gravity beer in Essex  <http://www.eminent.demon.co.uk

Re: why use a class

A good example for OO is the 'Person' class.

All Persons have name, address, telephone number etc.  You create a
class that encapsulartes these variables, with getter and setter
methods for using them.

If you then needed to extend their functionality, for example to have
classes that dealt with Students and Lecturers, you would have half of
the functionality already built.  The student and lecturer classes
would EXTEND or INHERIT (key words to learn about) all of the
functionality of the Person class, but you could add relevent
functionality for the student and lecturer classes
(getCoureseworkResults(), getAttendence() for student for example).

An exampe for PHP; you could create some sort of SQL writing class,
then create SUBCLASSES for Oracle, MySQL and Postregsql integration -
the SQL development would be inherited from the SQL writing class but
the bit that communicates with the db and executes the SQL would be
developed in the SUB CLASS (also known as CHILD CLASS).

The key strength is in maintainability.  If you had just written the
SQL writing code and copy and pasted it into 3 functions for writing to
the various DBMS and you found an error, you would have to correc it in
3 places.  If you had created a set of classes, then you would only
have to update it in one place.

Now in PHP with include files you *can* possibly achieve a similar
level of reusablity (I can't think why not but my gut instinct tells me
it must be flawed in some way), but OO is a nice and neat way of
achieving it.

The beauty of OO from a conceptual perspective is that you can model a
project in terms of things that can relate to the real world; persons,
chairs, products and so on.  It can help in understanding how these
things interact and therfore in assists in planning the code.

Have a look at class diagrams and UML for some ways of modelling and
planning code - the bigger the project the more the benefit is from
approaching the development in a formal and structured way.

Hope this helps,


Site Timeline