Educate me please - on Classes
Moderator: General Moderators
Educate me please - on Classes
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?
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
No, there's also nothing you cannot do with pure assembly, but it sure does make your job more complicated.agtlewis wrote: Am I wrong?
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?
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
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
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
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.
This is a simple example but it uses other functions such as..
And...
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;
}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();
}Code: Select all
/***************************************************************************
MICROTIME GENERATOR
***************************************************************************/
function MicroTimeFloat() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}- shiznatix
- DevNet Master
- Posts: 2745
- Joined: Tue Dec 28, 2004 5:57 pm
- Location: Tallinn, Estonia
- Contact:
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
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
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".
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".
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Code: Select all
## show smiley pack
require_once 'class/text.class.php';
$text = new text();
echo $text->getSmileyPack($theperson);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
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
- AKA Panama Jack
- Forum Regular
- Posts: 878
- Joined: Mon Nov 14, 2005 4:21 pm
Actually you could do the same thing without a class.scrotaye wrote:i allow my users to choose which set of smilies they use throughout the site.Code: Select all
## show smiley pack require_once 'class/text.class.php'; $text = new text(); echo $text->getSmileyPack($theperson);
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
Code: Select all
## show smiley pack
require_once 'function/getSmileyPack.php';
echo getSmileyPack($theperson);Code: Select all
<?php
if (!function_exists('getSmileyPack')) {
function getSmileyPack($theperson)
{
// your code
}
}
?>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();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.
Last edited by AKA Panama Jack on Tue Mar 07, 2006 4:52 am, edited 2 times in total.
- AKA Panama Jack
- Forum Regular
- Posts: 878
- Joined: Mon Nov 14, 2005 4:21 pm
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.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.
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.
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.
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.
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.AKA Panama Jack wrote: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.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.
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.
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.
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
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.
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.
(#10850)
- AKA Panama Jack
- Forum Regular
- Posts: 878
- Joined: Mon Nov 14, 2005 4:21 pm
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.patrikG wrote: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.AKA Panama Jack wrote: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.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.
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.
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.
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: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.
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.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.
On a precautionary sidenote: if this becomes a flamefest, we will be missing out on some fun in life.