Wednesday, October 10, 2007

Simple PHP Class Example Part 1

$item = new Items;
$item -> setName("Book");
$book = $item->getName();

$item -> setName("Pencil");
$Pencil = $item->getName();

class Items
{
var $item;

function setName($newname)
{
$this->title=$newname;
}

function getName()
{
return $this->title;
}
}

Simple PHP Class Example Part 2

/*Create a new Object*/
$pricelist = new PriceList;

/*Set item name and price*/
$pricelist-> setItem("Carrot",10);

/*Get Item information*/
$itemname = $pricelist->getItemName();
$itemprice = $pricelist->getItemPrice();
$iteminfo = $pricelist->getItemInfo();

/*Display Item Information*/
echo "Name: $itemname \n";
echo "Price: $itemprice
\n";
echo "Item Information: $iteminfo
\n";
/*
OUTPUT
Name: Carrot
Price: 10
Item Information: Item=Carrot, Price=10
*/

/* This is the class object */
/* The Class name is "PriceList"*/
class PriceList
{
var $item; // -> this will hold the item name
var $price; // -> this will hold the item price
var $iteminfo; // -> this will hold the item info

/* This function will set the item name and price and store them in "inteminfo"*/
function setItem($newitem, $newprice)
{
$this->item=$newitem;
$this->price=$newprice;
$this->iteminfo = "Item=".$this->item.", Price=".$this->price;
}
/* This function will return the item info of the object */
function getItemInfo()
{
return $this->iteminfo;
}
/* This function will return the item name of the object */
function getItemName()
{
return $this->item;
}
/* This function will return the item price of the obj*/
function getItemPrice()
{
return $this->price;
}
}