Page 1 of 2

Educate me please - on Classes

Posted: Mon Mar 06, 2006 10:21 pm
by Benjamin
I was wondering if some of you could please help me understand classes and what the benefits of using them are. I am in a position where I can build pretty much anything and I have never had to use classes. I generally write functions which in turn call other functions and have never had a problem with that.

My function calls might seem complex to others, as I will send a few arrays and some variables to a function and return an array, but it's simple to me and I understand it.

Honestly, (and I might be wrong) I don't think there is anything I couldn't do without using a class. Am I wrong?

Re: Educate me please - on Classes

Posted: Mon Mar 06, 2006 11:50 pm
by josh
agtlewis wrote: Am I wrong?
No, there's also nothing you cannot do with pure assembly, but it sure does make your job more complicated.

Give us an example of something you are doing with normal functions and we'll point out why or why not a class would be better in the specific examples. Your question really is too vague, but let's say a template system? A forum system? A blog? An input validation script? An MVC?

Posted: Tue Mar 07, 2006 1:30 am
by s.dot
I recently (very recently) had the same inquiry as you. Then i started writing and using classes and I noticed two differences.

1) it cuts back on the amount of code you need to use (and potential errors by constantly writing the same code over and over)

2) it groups together functions and gives your code a better readability (and understanding when you're coding it)

I'll even add one more

$this->doFunction($data) looks pretty cool ;-D

Posted: Tue Mar 07, 2006 2:18 am
by Benjamin
Ok, I don't want to post too much of my code but here is a very simple example. Most of the code I write is much more complex. I have functions that call each other and both of the functions have nested if and while loops. It just makes sense to me. I have never ran into a problem coding like that. This is a function I wrote to get data from a database, all the functions below it are dependencies.

Code: Select all

/***************************************************************************
                         GET DATA FROM THE DATABASE
***************************************************************************/

function GetMySQLData($Fields, $Table, $Parameters, $Limit) {
  Global $Connect, $PageData;
  $Start = MicroTimeFloat();
  $Query = "select ";
  $Fields = explode(" ", $Fields);
  $FieldCount = count($Fields) - 1;
  for ($CreateField = 0; $CreateField <= $FieldCount; $CreateField++) {
    $Query .= "`" . mysql_real_escape_string($Fields[$CreateField]) . "`, ";
  }
  $Query = substr($Query, 0, -2) . " from `" . mysql_real_escape_string($Table) . "` ";
  if ($Parameters != "") {
    $Query .= "where";
    while (list($Field, $Value) = each($Parameters)) {
      $Value = explode(" ", $Value);
      $Query .= " `" . mysql_real_escape_string($Field) . "` " . mysql_real_escape_string($Value[0]) . " '" . mysql_real_escape_string($Value[1]) . "' and ";
    }
  $Query = substr($Query, 0, -4);
  }
  if ($Limit != "") {
    $Query .= "limit " . mysql_real_escape_string($Limit);
  }
  if (!$Resource = @mysql_query($Query,$Connect)) {
    if (DEBUG_MODE == true) {
      $Message = "5<br /><br /><b style='color: #ff0000'>Database Query Error!</b><br /><br />Query: " . $Query . "<br /><br />Returned Error: " . mysql_errno() . " " . mysql_error();
      CallFatalError($Message);
    } else {
      CallFatalError('5 General Database Update');
    }
  } else {
    $Record = 0;
    while ($Data = mysql_fetch_assoc($Resource)) {
      $Records[$Record] = $Data;
      $Record++;
    }
    $Records['NumRows'] = mysql_num_rows($Resource);
  }
  $End = MicroTimeFloat();
  $PageData['QueryTime'] = $PageData['QueryTime'] + ($End - $Start);
  $PageData['TotalQueries']++;
  @mysql_free_result($Resource);
  return $Records;
}
This is a simple example but it uses other functions such as..

Code: Select all

/***************************************************************************
  IN CASE SOMETHING GOES HORRIBLY WRONG, THIS MAY BE THE ONLY FUNCTION
  WE CAN FALL BACK ON...
***************************************************************************/

function CallFatalError($ErrorNumber) {
@ob_end_clean();
?>
<html><head><title>Website Update In Progress</title></head>
<body>
<h1>System Update In Progress</h1>
<p>The page you are trying to view is currently being updated.  Please try again later.</p>
<p>Message #: <?php echo $ErrorNumber; ?></p>
</body>
</html>
<?php
die();
}
And...

Code: Select all

/***************************************************************************
                            MICROTIME GENERATOR
***************************************************************************/

function MicroTimeFloat() {
   list($usec, $sec) = explode(" ", microtime());
   return ((float)$usec + (float)$sec);
}

Posted: Tue Mar 07, 2006 2:26 am
by shiznatix
i recently had to start using classes and it was a bit painful for me to really get into it and start knowing how to do it. I had to write a class for this CMS thing and I did everything with procedual code inside the class. Then I went back over it and did some organizing and cleaning up. Then I went over it again and made it more OO. Then I cleaned up that and now I have a nice class that is some decent OOP. After that I was able to understand how classes make your life oh so much easier. I had to go back and add some features and if I had kept it in procedual it would have been horrible. It just made my life so much easier I could not believe it.

That is my story on the 'why use classes'.

Also, when you code in OOP it looks good on your resume.

and scrotaye is right, when you write somthing like $this->doFunction($data) it makes you feel really smart :wink:

Posted: Tue Mar 07, 2006 2:35 am
by s.dot
another advantage is...

instead of hardcoding your functions into every page that you use them on, (or including a file like functions.php that contains lots of irrelevant functions) you can call in only the set of functions (class) that you need for that particular area of coding.

i think the bottom line is convenience and scalabilty

say you wanted to change something.. which is easier? editing your class.. or editing 20 hardcoded scripts?

Edit: It may sound like i'm being totally pro OOP, but I'm not. If procedural coding works best for you then go for it. "If it ain't broke, don't fix it".

Posted: Tue Mar 07, 2006 2:42 am
by Benjamin
Ok, I understand that you have had good experiences with classes. But can you show me a dumbed down example? I have read the examples in PHP books but they have never seemed relevent to anything I would ever use. Sorry If I am being dense.

Posted: Tue Mar 07, 2006 2:49 am
by s.dot

Code: Select all

## show smiley pack
require_once 'class/text.class.php';
$text = new text();
echo $text->getSmileyPack($theperson);
i allow my users to choose which set of smilies they use throughout the site.
mind you, these smilies will be shown on lots of pages, forums, blogs, messages, etc

instead of querying for their preference, doing a big if/else statement, and returning the correct set of smileys every time i need to call them.. i can condense it into that three lines of code.

then later on down the line if I need to change the smiley pack for some reason (like adding more) i just edit 1 area (the class) and it will reflect the changes throughout my whole site

Posted: Tue Mar 07, 2006 4:37 am
by AKA Panama Jack
scrotaye wrote:

Code: Select all

## show smiley pack
require_once 'class/text.class.php';
$text = new text();
echo $text->getSmileyPack($theperson);
i allow my users to choose which set of smilies they use throughout the site.
mind you, these smilies will be shown on lots of pages, forums, blogs, messages, etc

instead of querying for their preference, doing a big if/else statement, and returning the correct set of smileys every time i need to call them.. i can condense it into that three lines of code.

then later on down the line if I need to change the smiley pack for some reason (like adding more) i just edit 1 area (the class) and it will reflect the changes throughout my whole site
Actually you could do the same thing without a class.

Code: Select all

## show smiley pack
require_once 'function/getSmileyPack.php';
echo getSmileyPack($theperson);
You edit one function file and it reflects the same thing throughout the site. Most places people use classes are not needed and only add overhead to the system. Plus you can be just as scalable, formatted and easy to read/expand without classes. And if you are worried about redeclaring the same function, something that only happens through really sloppy coding, you can wrap your function like this...

Code: Select all

<?php
if (!function_exists('getSmileyPack')) {
	function getSmileyPack($theperson)
	{
		// your code
	}
}
?>
One good reason to use classes is if your project uses a bunch of different modules but you want to use the same function call.

Here is an example...

Code: Select all

$debris_type = $row['debris_type'];
if(!class_exists($debris_type)){
	include ("class/debris/" . $debris_type . ".inc");
}
$debrisobject = new $debris_type();
$debrismessage = $debrisobject->show_debris_code();
This is from a game I am working on where there are over 15 different types of debris. By using classes I can create more debris items without changing any of the core game code. With the above snippet of code I could have a loop that selects 3 different items and loads each items class. Then it executes the same function in each class.

If I used functions like I mentioned earlier I would have to use a different function name for each item because I couldn't declare the same function multiple times. By wrapping the function in a class the function can be declared multiple times.

That's one of the best uses for classes... Creating modules for different things so you can have a small core code that accesses all of the class modules. Just wrapping everything in a class is a total waste of time and resources and usually slows down the system because of the way PHP handles classes. For the most part stick with using functions and use classes where they would really help.

Posted: Tue Mar 07, 2006 4:48 am
by AKA Panama Jack
scrotaye wrote: instead of hardcoding your functions into every page that you use them on, (or including a file like functions.php that contains lots of irrelevant functions) you can call in only the set of functions (class) that you need for that particular area of coding.
Actually, it doesn't matter if you are using a function.php or a class. In both cases you can be loading in a bunch of irrelevant functions that you don't need just to use one set of functions. Just as with a class you need to break down everything into modules that can be loaded as needed. It doesn't matter if you are using classes or functions.

Your pages will load faster if you include 100 individual include files for functions instead of including one class that contained 100 functions. If you included 100 individual classes it would be even slower still.

And remember your class is going to allocate far more system resources for all of the functions inside a class than it would if the same functions were not wrapped inside a class.

Posted: Tue Mar 07, 2006 6:15 am
by jmut
I think this is going way off track.
Class is not about piling up n number of functions together.
It's about inheritance, polymorphism, design patterns etc. (very basic said of course)
These are the things that really make (might make) classes the preferable choice.
Adding flexibility , isolation (this black box every book talks about) to the code.
This is very basic explonation of course but to my experience OOP is far from bunch of functions in one place.

Posted: Tue Mar 07, 2006 7:21 am
by patrikG
AKA Panama Jack wrote:
scrotaye wrote: instead of hardcoding your functions into every page that you use them on, (or including a file like functions.php that contains lots of irrelevant functions) you can call in only the set of functions (class) that you need for that particular area of coding.
Actually, it doesn't matter if you are using a function.php or a class. In both cases you can be loading in a bunch of irrelevant functions that you don't need just to use one set of functions. Just as with a class you need to break down everything into modules that can be loaded as needed. It doesn't matter if you are using classes or functions.

Your pages will load faster if you include 100 individual include files for functions instead of including one class that contained 100 functions. If you included 100 individual classes it would be even slower still.

And remember your class is going to allocate far more system resources for all of the functions inside a class than it would if the same functions were not wrapped inside a class.
As jmut said: this is uninformed information and contains many false statements. OOP can't be learned in a day, or a week, it's complex and helps you break down complexity. It's a bit like learning Latin: you hate it at first, but once you've stepped over a certain threshold, you will see many things much clearer and understand.

The benefits of OOP vs. Procedural have been discussed to no end on many discussion boards. One classic post is

http://www.sitepoint.com/forums/showpos ... stcount=14

Another post, not as eloquent and more basic than the above one

viewtopic.php?t=8873

Buy yourself a book, I recommend http://www.sitepoint.com/books/phpant1/ which does a good job at giving a solid introduction.

Once you believe you have a fairly good grasp, look at http://www.phppatterns.com

Probably the best example of OOP in PHP4 (not PHP5, mind you) is: http://sourceforge.net/projects/eclipselib

Download it and look at the code. Start using it - if only for the DB layer alone, which is stunning in its simplicity.

Posted: Tue Mar 07, 2006 1:23 pm
by Christopher
The discussion of Procedural vs OO programming can be interesting, but ususally is not. ;) The thing that usually does not get discussed (amid the flames) is that design is really the important thing in software development. Good design is a beautiful thing, and all of us understand that our designs get better and better the more we program. We are constantly refactoring our code as we learn new things. So to segue into OO -- the reason it exists at all is that some really smart programmers who were really great designers wanted some more ways to express in code the design ideas they had. It's not a evil plot -- really!

Which takes me to the code that you posted. What you posted is called a Transaction Script -- which is a fancy name for some code that does a bunch of thing together to produce a result. Your function GetMySQLData() does three main things. It get data from a data source, it generates HTML output from that, and it does timings on the process. All the code is interdependent on each other. So the two things that spring to mind when looking at it are Separation of Concerns and Dependencies. Those three different things really should be separated. I doesn't matter whether they become functions or classes. Separating them will make them easier to test and debug -- and it will also promote code reuse (DRY) because you might find that you can use those parts elsewhere. As for dependencies, the pervailing wisdom is that the data access functions/classes should not be dependent on any other code -- so the HTML generator would know about the data accessor, but not vice versa. Finally the timing code should be moved outside where it can be removed more easily for production use.

Posted: Tue Mar 07, 2006 1:29 pm
by AKA Panama Jack
patrikG wrote:
AKA Panama Jack wrote:
scrotaye wrote: instead of hardcoding your functions into every page that you use them on, (or including a file like functions.php that contains lots of irrelevant functions) you can call in only the set of functions (class) that you need for that particular area of coding.
Actually, it doesn't matter if you are using a function.php or a class. In both cases you can be loading in a bunch of irrelevant functions that you don't need just to use one set of functions. Just as with a class you need to break down everything into modules that can be loaded as needed. It doesn't matter if you are using classes or functions.

Your pages will load faster if you include 100 individual include files for functions instead of including one class that contained 100 functions. If you included 100 individual classes it would be even slower still.

And remember your class is going to allocate far more system resources for all of the functions inside a class than it would if the same functions were not wrapped inside a class.
As jmut said: this is uninformed information and contains many false statements. OOP can't be learned in a day, or a week, it's complex and helps you break down complexity. It's a bit like learning Latin: you hate it at first, but once you've stepped over a certain threshold, you will see many things much clearer and understand.
Actually nothing I mentioned was uninformed or false. One of the things I do is heavy testing of both OOP and Proceedural and I have given examples in the past of why OOP is not to be used for everything but only for targetted jobs when being used in PHP. I have been testing these things for a very long time and I have the experience to back up my statements. :)

Also, don't scare the person off by claiming OOP is more complex. It really isn't. It's actually fairly easy once you know just a few of the basics.

If you can prove me wrong then please go ahead but I think you will find I know exactly what I am talking about. :)

Posted: Tue Mar 07, 2006 1:44 pm
by patrikG
AKA Panama Jack wrote:Actually nothing I mentioned was uninformed or false. One of the things I do is heavy testing of both OOP and Proceedural and I have given examples in the past of why OOP is not to be used for everything but only for targetted jobs. I have been testing these things for a very long time and I have the experience to back up my statements. :)
Reading your post I quoted above, what lingers is that classes are functions by a different name. They are not, functions are called methods and, while we don't need to discuss what's faster and what isn't (because it has been done ad nauseam), OOP helps see complexity of software design and break it down more easily than procedural does if applied properly. You can structure procedural code and use methodolgies of OOD, but in the end, OOP has brought about a change in how software is being developed.
AKA Panama Jack wrote:Also, don't scare the person off by claiming OOP is more complex. It really isn't. It's actually fairly easy once you know just a few of the basics.
I wasn't using the comparative with regards to "complex". But if you want: OOP is more complex than procedural coding as it involves a change of perspective of how you desing software. You develop something akin to a "meta-perspective". That alone is helpful, but, as has been said many, many, many, many times: OOP is not the alpha and omega. However, as a software developer, you have to know the tools of trade and OOP is one of them.

On a precautionary sidenote: if this becomes a flamefest, we will be missing out on some fun in life.