...

View Full Version : Classes vs Functions



musher
08-24-2006, 07:45 PM
Ok I've done some searchin and some reading, I kind of understand what a class is and sort of how they work (the code inside a few that I've been playing with makes sense, even made some changes to them), but I dont get the basic concept of why. (I think I'm not getting the basic princepal about classes and there use)

why use classes rather then functions?
example I have a function for opening a table getting records to build a drop-down, ive seen classes that do the same thing

Spookster
08-24-2006, 08:29 PM
Well you cannot compare classes to functions. They are not the same thing. Classes are a key component of object oriented programming. Classes contain functions. A class is a blueprint of an object. In that blueprint are functions that perform the various tasks of that class. When you want to create an object you create an instance of that class of which you have various functions within that class to perform various tasks that the object should perform.

musher
08-24-2006, 09:41 PM
ok that makes sense, well sort of. A class kind of defines an object ??? then whats an object and/or whats object oriented programming (layman terms please).

Spookster
08-24-2006, 09:55 PM
http://en.wikipedia.org/wiki/Object-oriented_programming

Beagle
08-24-2006, 10:52 PM
We can try some analogies, though I'm not sure this should turn into an academic lecture:

A class defines an object, an object is an instance of a class. Objects are like objects in the real world. Classes are like definitions in the real world. Classes are abstract, objects are concrete. If you know Plato, the forms are analogous to classes, and the objects are the real things in the real world. So you can have a table, or you can have a design for a table. The design for each table is the same in your factory, but you make blue tables that are 9x5x2 and you make red tables that are 10x10x5 and you make green tables that are 4x4x8. Each table is from the same design of a table. Same thing here, you have a class that defines what an object is, but the object has freedom to become what it wants to.

So with functions, you need to have lots of variables that store all this information, but don't group them strictly, whereas with objects, every object will always have those variables inside them, you always know how to get them, etc.

Methods within an object have access the variables only for their object and for no other object. So I ask a table what color it is and it says red. In a procedural world (what you're talking about with just functions) I would ask the world what color that table over there is. And here's where sloppy coding can bite you.

OO is just a design paradigm. There isn't anything you can do in OO that you couldn't conceivably to in procedural programming. OO just makes it harder to screw up and easier to write.

saecula
08-24-2006, 10:59 PM
Classes also persist from initialization to end of script, functions can only exist linearly within the constriants of the script.

musher
08-25-2006, 06:14 PM
First thanks all for the info has helped shed some light, link was good thanks Spookster.

Here's a sample page from some stuff I'm playing with, I writing my own cms as a learning project. Most pages use the same basic code sections (look identical except for the actual field/variable names, and validation stuff). Sample below has menu_title, default_submenu, display_order, link_url were the section for page content would have menu_title, page_content etc for fields. common.inc has all the common functions for the site.

Were (how) would I want to implement classes on something like this?



<?php
session_start();
// Security Check
include_once("includes/common.inc");
include_once("includes/seccheck.inc");
// Open DB
require_once('../includes/MySQLConn.inc');
// Get Site Parameters
require_once('includes/siteparms.inc');
// Global Variable Setup for Validation routines
$var_section_name = "Site Menu (Page)";
$var_message = "Select a " .$var_section_name. " or Add a new " .$var_section_name. ".";
$_errLvl="N";
$_parm_title_class = "ok_cls";
$_parm_submenu_class = "ok_cls";
$_parm_order_class = "ok_cls";
$_parm_link_url = "ok_cls";
$hold_menu_title = "";
$hold_default_submenu = "";
$hold_display_order = "";
$hold_link_url = "";
// Form/Field Validation
if ((isset($_POST["REC_insert"])) OR (isset($_POST["REC_update"]))) {
$hold_message = ' ';
$_checkname=$_POST['menu_title'];
if (f_CheckInputData($_checkname,true)) {
$hold_menu_title = "";
$_parm_title_class = "error_cls";
$hold_message = $hold_message.'<br /> - Please enter a Menu Title';
$_errLvl="Y";
}else{
$hold_menu_title = $_POST['menu_title'];
$_parm_title_class = "ok_cls";
}
$_checkname=$_POST['default_submenu'];
if (f_CheckInputData($_checkname,true)) {
$hold_default_submenu = "";
$_parm_submenu_class = "error_cls";
$hold_message = $hold_message.'<br /> - Please enter a Default SubMenu Title (This is the sub menu that will be selected as a default)';
$_errLvl="Y";
}else{
$hold_default_submenu = $_POST['default_submenu'];
$_parm_submenu_class = "ok_cls";
}
$_checkname=$_POST['display_order'];
if (f_CheckInputData($_checkname,true,"numeric")) {
if (isset($_POST["display_order"])){
$hold_display_order = $_POST["display_order"];
}else{
$hold_display_order = "";
}
$_parm_order_class = "error_cls";
$hold_message = $hold_message.'<br /> - Please enter a Display Order (must be numeric ie. 1-999)';
$_errLvl="Y";
}else{
$hold_display_order = $_POST['display_order'];
$_parm_order_class = "ok_cls";
}
if (isset($_POST["link_url"])){
$hold_link_url = $_POST["link_url"];
}else{
$hold_link_url = "";
}
if ($_errLvl == "Y") {
if (isset($_POST["REC_insert"])){
$_REQUEST["add"] = "yes";
$var_message = '<u>Please Correct the following ERRORS:</u>'.$hold_message;
} else {
$_holdID = $_POST['id'];
$_REQUEST["edit"] = "yes";
$var_message = '<u>Please Correct the following ERRORS:</u>'.$hold_message;
}
}
}
// SQL Functions (Form Processing sections (Add/Insert, Modify/Edit, Delete))
// -- SQL to Insert a new record
if ((isset($_POST["REC_insert"])) && ($_errLvl == "N")) {
$sql = sprintf("INSERT INTO menu (menu_title,default_submenu,link_url,display_order) VALUES (%s, %s, %s, %s)",
GetSQLValueString($_POST['menu_title'], "text"),
GetSQLValueString($_POST['default_submenu'], "text"),
GetSQLValueString($_POST['link_url'], "text"),
GetSQLValueString($_POST['display_order'], "text"));
$result = mysql_query($sql);
$var_message = "New " .$var_section_name. " Record has been Added.";
}
// -- SQL to Modify/Edit a record
if ((isset($_POST["REC_update"])) && ($_errLvl == "N")) {
$sql = sprintf("UPDATE menu SET menu_title=%s, default_submenu=%s, link_url=%s, display_order=%s WHERE ID=%s",
GetSQLValueString($_POST['menu_title'], "text"),
GetSQLValueString($_POST['default_submenu'], "text"),
GetSQLValueString($_POST['link_url'], "text"),
GetSQLValueString($_POST['display_order'], "text"),
GetSQLValueString($_POST['id'], "int"));
$result = mysql_query($sql);
$var_message = "The " .$var_section_name. " information has been Updated.";
}
// -- SQL to Delete a record
if ((isset($_REQUEST["delete"])) && ($_REQUEST["delete"] == "yes")) {
$id=$_GET['recordID'];
$sql = "DELETE FROM menu WHERE ID=$id";
$result = mysql_query($sql);
$var_message = "The " .$var_section_name. " information has been Deleted.";
}
?>
<!-- http://test.com/quirksmode -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>// Site Management System - <?php echo $var_section_name; ?> // <?php echo $var_SiteName_parm; ?>//</title>
<?php include_once("includes/metatags.inc"); ?>
<style type="text/css" media="screen">@import "stylesheets/default.css";</style>
<!--[if IE]>
<link href="stylesheets/default-IE.css" rel="stylesheet" type="text/css" media="screen">
<![endif]-->
</head>
<body>
<div id="header">
<?php include_once'includes/header.inc';?>
</div>
<div id="content">
<h2><?php echo $var_SiteName_parm; ?> - <?php echo $var_section_name; ?> Maintenance</h2>
<hr>
<table width="98%" border="1" cellpadding="2">
<?php
// Display Record
if ((isset($_REQUEST["display"])) && ($_REQUEST["display"] == "yes")) {
$var_message = $var_section_name." Record Display";
$var_id = $_GET['recordID'];
$result = mysql_query("SELECT * FROM menu WHERE ID=$var_id",$db);
$MyRow = mysql_fetch_array($result);
echo '<form method="post" name="DisplayForm" action="'.$_SERVER['PHP_SELF'].'">';echo"\r\n";
echo '<tr><td colspan="2" class="msgblock">'.$var_message.'</td></tr>';echo"\r\n";
echo '<tr><td class="colmhdr">Menu Title: </td><td><input type="Text" name="menu_title" value="'.$MyRow['menu_title'].'" size="50" maxlength="50" readonly="true" /></td></tr>';echo"\r\n";
echo '<tr><td class="colmhdr">Default SubMenu: </td><td><input type="Text" name="default_submenu" value="'.$MyRow['default_submenu'].'" size="50" maxlength="50" readonly="true" /></td></tr>';echo"\r\n";
echo '<tr><td class="colmhdr">Display Order: </td><td><input type="Text" name="display_order" value="'.$MyRow['display_order'].'" size="3" maxlength="3" readonly="true" /></td></tr>';echo"\r\n";
echo '<tr><td class="colmhdr">** Special URL ** </td><td><input type="Text" name="link_url" value="'.$MyRow['link_url'].'" size="87" maxlength="250" readonly="true" /></td></tr>';echo"\r\n";
echo '<tr><td colspan="2">&nbsp;</td></tr>';echo"\r\n";
echo '<tr>';
echo '<td><input type="button" value="Edit '.$var_section_name.'" onclick="location.href=\''.$_SERVER['PHP_SELF'].'?recordID='.$MyRow['ID'].'&edit=yes\'" /></td>';
echo '<td><input type="button" value="Return to Select" onclick="location.href=\'' .$_SERVER['PHP_SELF']. '\'" /></td>';
echo '</tr>';echo"\r\n";
echo '</form>';echo"\r\n";
}
// Add/Insert Record Form
elseif ((isset($_REQUEST["add"])) && ($_REQUEST["add"] == "yes")) {
if ($_errLvl == "N"){
$var_message = "Add a New ".$var_section_name;
}
echo '<form method="post" name="AddForm" action="'.$_SERVER['PHP_SELF'].'">';echo"\r\n";
echo '<tr><td colspan="2" class="msgblock">'.$var_message.'</td></tr>';echo"\r\n";
echo '<tr><td class="'.$_parm_title_class.'">Menu Title: </td><td><input type="Text" name="menu_title" value="'.$hold_menu_title.'" size="50" maxlength="50" /></td></tr>';echo"\r\n";
echo '<tr><td class="'.$_parm_submenu_class.'">Default SubMenu: </td><td><input type="Text" name="default_submenu" value="'.$hold_default_submenu.'" size="50" maxlength="50" /></td></tr>';echo"\r\n";
echo '<tr><td class="'.$_parm_order_class.'">Display Order: </td><td><input type="Text" name="display_order" value="'.$hold_display_order.'" size="3" maxlength="3" /></td></tr>';echo"\r\n";
echo '<tr><td class="'.$_parm_link_url.'">** Special URL ** </td><td><input type="Text" name="link_url" value="'.$hold_link_url.'" size="87" maxlength="250" /></td></tr>';echo"\r\n";
echo '<tr><td colspan="2">&nbsp;</td></tr>';echo"\r\n";
echo '<tr><td><input type="submit" name="submit" value="Submit"></td>';
echo '<td><input type="button" value="Return to Select" onclick="location.href=\'' .$_SERVER['PHP_SELF']. '\'" /></td></tr>';echo"\r\n";
echo '<input type="hidden" name="REC_insert" value="form3">';
echo '</form>';echo"\r\n";
}
// Modify/Edit Record Form
elseif ((isset($_REQUEST["edit"])) && ($_REQUEST["edit"] == "yes")) {
if ($_errLvl == "N"){
$id = $_GET['recordID'];
$var_message = "Edit ".$var_section_name;
} else {
$id = $_holdID;
}
$result = mysql_query("SELECT * FROM menu WHERE ID=$id",$db);
$MyRow = mysql_fetch_array($result);
if (($hold_menu_title =="") && ($hold_default_submenu == "") && ($hold_display_order == "")) {
$hold_menu_title=$MyRow['menu_title'];
$hold_default_submenu=$MyRow['default_submenu'];
$hold_display_order=$MyRow['display_order'];
$hold_link_url=$MyRow['link_url'];
}
echo '<form method="post" name="EditForm" action="'.$_SERVER['PHP_SELF'].'">';
echo '<tr><td colspan="2" class="msgblock">'.$var_message.'</td></tr>';echo"\r\n";
echo '<tr><td class="'.$_parm_title_class.'">Menu Title: </td><td><input type="Text" name="menu_title" value="'.$hold_menu_title.'" size="50" maxlength="50" /></td></tr>';echo"\r\n";
echo '<tr><td class="'.$_parm_submenu_class.'">Default SubMenu: </td><td><input type="Text" name="default_submenu" value="'.$hold_default_submenu.'" size="50" maxlength="50" /></td></tr>';echo"\r\n";
echo '<tr><td class="'.$_parm_order_class.'">Display Order: </td><td><input type="Text" name="display_order" value="'.$hold_display_order.'" size="3" maxlength="3" /></td></tr>';echo"\r\n";
echo '<tr><td class="'.$_parm_link_url.'">** Special URL ** </td><td><input type="Text" name="link_url" value="'.$hold_link_url.'" size="87" maxlength="250" /></td></tr>';echo"\r\n";
echo '<tr><td colspan="2">&nbsp;</td></tr>';echo"\r\n";
echo '<tr><td><input type="submit" name="submit" value="Submit" /></td>';
echo '<td><input type="button" value="Return to Select" onclick="location.href=\'' .$_SERVER['PHP_SELF']. '\'" /></td></tr>';echo"\r\n";
echo '<input type=hidden name="id" value="'.$MyRow['ID'].'">';
echo '<input type="hidden" name="REC_update" value="form2">';
echo '</form>';echo"\r\n";
}
// Show Record List (Menu Section Record Selection Page)
else {
$result = mysql_query("SELECT * FROM menu ORDER BY display_order",$db);
if ($MyRow = mysql_fetch_array($result)) {
// Display list if there are records to display
echo '<form name="SelectForm" action="" method="post">';echo"\r\n";
echo '<tr><td colspan="6" class="msgblock">'.$var_message.'</td></tr>';echo"\r\n";
echo '<tr>';
echo '<td colspan="3">';
echo '<div align="center"><input type="button" value="Add '.$var_section_name.'" onclick="location.href=\'' . $_SERVER['PHP_SELF'] . '?add=yes\'" /></div>';
echo '</td>';
echo '<td class="colmhdr">Menu Title</td>';
echo '<td class="colmhdr">Default SubMenu</td>';
echo '<td class="colmhdr">Display Order</td>';
echo '</tr>';echo"\r\n";
do {
echo '<tr>';
echo '<td><input type="button" value="Edit" onclick="location.href=\''.$_SERVER['PHP_SELF'].'?recordID='.$MyRow['ID'].'&edit=yes\'" /></td>';
echo '<td><input type="button" value="Display" onclick="location.href=\''.$_SERVER['PHP_SELF'].'?recordID='.$MyRow['ID'].'&display=yes\'" /></td>';
echo '<td><input type="submit" onclick="this.form.action=\''.$_SERVER['PHP_SELF'].'?recordID='.$MyRow['ID'].'&delete=yes\';return confirm(\'Are you sure you want to delete this record\')" value="Delete" name="del" /></td>';
echo '<td>'.$MyRow['menu_title'].'</td>';
echo '<td>'.$MyRow['default_submenu'].'</td>';
echo '<td>'.$MyRow['display_order'].'</td>';
echo '</tr>';echo"\r\n";
} while ($MyRow = mysql_fetch_array($result));
echo '</form>';echo"\r\n";
} else {
// No records to display
$var_message = "Sorry, no ".$var_section_name." records were found!";
echo '<form name="NoRecForm" action="" method="post">';echo"\r\n";
echo '<tr><td colspan="6" class="msgblock">'.$var_message.'</td></tr>';echo"\r\n";
echo '<tr>';
echo '<td colspan="3">';
echo '<div align="center"><input type="button" value="Add '.$var_section_name.'" onclick="location.href=\'' . $_SERVER['PHP_SELF'] . '?add=yes\'" /></div>';
echo '</td>';
echo '<td class="colmhdr">Menu Title</td>';
echo '<td class="colmhdr">Default SubMenu</td>';
echo '<td class="colmhdr">Display Order</td>';
echo '</tr>';echo"\r\n";
echo '<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>';echo"\r\n";
echo '</form>';echo"\r\n";
}
}
?>
</table>
</div>
<div id="sidebar"><?php include_once'includes/sidebar_menu.inc';?></div>
<div id="footer">
<?php include_once'includes/footer.inc';?>
</div>
</body>
</html>
<?php
mysql_close($db);
?>

Beagle
08-28-2006, 05:05 PM
class Page
{
var $m_siteName; // *** IN php 5 you can do: public $m_siteName;
var $m_sectionName; // **** In PHP 5 you can do: private $m_sectionName;

function Page() // *** in PHP5 this would be: public function __construct()
{
// initialize whatever you want.
}

function setSectionName($p_sectionName) // *** in PHP 5 you can do: public function ...
{
$this->m_sectionName = $p_sectionName;
}

function setSiteName($p_siteName)
{
$this->m_siteName = $p_siteName;
}

function getSiteName()
{
return $this->m_siteName;
}

function getSectionName()
{
return $this->m_sectionName;
}
}

$myPage = new Page();
$myPage->setSiteName('My Site');
$myPage->setSectionName('My Section');

<html>
<head>
<title><?php echo $myPage->getSiteName();?> - <?php echo $myPage->getSectionName();?></title>
</head>
<body>
</body>
</html>

chump2877
08-28-2006, 05:29 PM
function getSiteName()
{
return $this->m_siteName;
}

this function/method doesn't need an argument..:p

and you forgot:


function getSectionName()
{
return $this->m_sectionName;
}

in your class...

but really you could just say:

echo $myPage->m_siteName; and...
echo $myPage->m_sectionName;

to print the class property values, instead of creating the getSectionName() and getSiteName() methods...

Beagle
08-28-2006, 07:34 PM
hehe, sorry, that was a STUPID copy paste mistake, fixed!

And I provided the simple accessors and mutators as examples

musher
08-29-2006, 06:38 AM
Hey Thanks guys for all the help

GJay
08-29-2006, 09:19 AM
but really you could just say:

echo $myPage->m_siteName; and...
echo $myPage->m_sectionName;

you could, but a lot of people prefer not to. I was taught that class variables should be private (or treated as such), with public methods to access them and I've found very few situations that have made me want to do it differently (though using __get and __set in PHP-5 does allow for some 'cheating')

marek_mar
08-29-2006, 04:31 PM
It's called overloading...

Spookster
08-29-2006, 06:46 PM
It's called overloading...

I assume you mean function overloading? If so then what they have done is not called overloading. Function overloading is when you have multiple functions with the same name but with a different number/data type of parameters.

marek_mar
08-29-2006, 07:07 PM
Would it be better if I had written "they (as in the authors of PHP) call it overloading"? In PHP overloading is different for a reason. I may not know the reson but I feel like I have an idea why it is different.

Spookster
08-29-2006, 09:01 PM
Would it be better if I had written "they (as in the authors of PHP) call it overloading"? In PHP overloading is different for a reason. I may not know the reson but I feel like I have an idea why it is different.

Are you talking about this?
http://us3.php.net/overload

I hope they don't decided to stick with that. That will just confuse people.

What's going on here though seems to be just a basic variation on Java/C++ inheritance.

marek_mar
08-29-2006, 09:47 PM
They actually already decided to stick with it. That's how it's done in PHP5 and the part of the manual you linked to was for an extension for PHP4...



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum