Sunday, November 4, 2007

PHP and Classes

The simplest way to learn about classes in PHP:
Well let's start by defining what is a class:
A generalized category in object-oriented programming that describes a group of more specific items called objects.
A class provides a template for defining the behavior of a particular type of object. Objects of a given class are identicalto each other in form and behavior.
A class is a descriptive tool used in a program to define a set of attributes or servicesthat characterize any member (object) of the class.
Now let's define a class in PHP and use some of the objects function. Let's assume that our object is an associative array having its indexes named after a product table. having fields: ID, NAME, DESCRIPTION.
So we should start by creating the table called products:
CREATE TABLE `products` (
`id` TINYINT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 20 ) NOT NULL ,
`description` VARCHAR( 20 ) NOT NULL ,
PRIMARY KEY ( `id` )
)

CODE

//let's define our class, and a set of functions inside this class.
class productdb
{
//this function create an empty instance of an associative array
function EmptyObject()
{
$product=array('ID'=>NULL,'NAME'=>NULL,'DESC'=>NULL);
return $product;
}
//this function takes a primary key as an input and returns the complete set of values corresponding to that primary key
function GetRow($id)
{
$result=mysql_query("SELECT id,name,description from products WHERE id='$id'");
while($row=mysql_fetch_assoc($result))
{
$product['ID']=$row['id'];
$product['NAME']=$row['name'];
$product['DESC']=$row['description'];
return $product;
}
}
}
//Now let's learn how to use those classes....
//first let's create an instance of that class....
$myobj= new productdb;
//now let's create an empty object, that has the specification of the object described above...
$myproduct=$myobj->EmptyObject();
//Suppose our product table is filled with values....
$myproduct=$myobj->GetRow($id)
echo $myproduct['ID'] . $myproduct['NAME'] . $myproduct['DESC'];
?>
And basicaly that is the simplest way to understanding classes and using them.

No comments: