Welcome to WebProNews Breaking eBusiness and Search News
Advertise | Newsletter | Sitemap | News Feeds News Feed 
 WebProNews Search Part of the iEntry network iEntry inc. 

A Shopping Cart Class In PHP

Amrit Hallan
Expert Author
Published: 2004-09-15

WebProNews RSS Feed


Classes have eluded me (rather I have eluded them) since the beginning of my primitive programming days (remember Turbo C++?).

They have always hovered over the horizons. This hasn't nagged me much, for I've been managing without classes pretty well, but sooner or later I had to come in contact with them. So in the morning (and I hadn't slept the entire night) I executed a gut-wrenching plunge into the depths of classes, and the shopping cart class was the first thing I wrote. Although I have made content management systems and algorithmic quote generations in PHP, I had not added a shopping cart class code to my code repository. It was not as tough as I had envisaged. I could have done something simpler but scripts like "Hello world!" seem silly after a point.

A class, as what I make of it is, a container of sorts that not only contains the variables required to perform a task, but even the sub-tasks to achieve the main objective. So what do we need in a cart class? We need an array that can store item ids and their quantities, and we need some functions that help us add items, delete them, and change their quantities. It is always better to write down a list of things to be done and a list of things needed to accomplish that.

We begin our class like this:

<?php

class ShoppingCart {

     var $items;

}

?>


$items is going to be an associative array to hold the precious information. Now that we have declared the container array, we need a function to add items to it.

<?php

class ShoppingCart {

     var $items;

     function add_items($product_id, $qty)
     {
       $this->items[$product_id]=$qty;
     }
}

?>


This is as simple as it looks. It accepts a product id (here in this case we can store anything, even the name of the product), makes it a key element of the associative array $items and gives it a value $qty.

How do we use this class? Interestingly, whenever we declare a variable when programming, we declare it as a "type", for instance, an integer type, or a char type, or a string type. You can perform certain operations using these types. These types are nothing but pre-defined classes carrying their intrinsic characteristics. In this case (our shopping cart class), we'll define a variables as "ShoppingCart" in the following manner:

<?php

class ShoppingCart {

     var $items;

     function add_items($product_id, $qty)
     {
       $this->items[$product_id]=$qty;
     }
}

$cart = new ShoppingCart;

?>


The last line declares a new variable -- $cart -- of type ShoppingCart and it will inherit all the characteristics of this class. This variable inherits an associative array $items and a function, namely add_items() that lets it accept different values. Let's add some items to our newly defined ShoppingCart variable:

<?php

class ShoppingCart {

     var $items;

     function add_items($product_id, $qty)
     {
       $this->items[$product_id]=$qty;
     }
}

$cart = new ShoppingCart;

$cart->add_items("Apples", 5);
$cart->add_items("Oranges", 15);
$cart->add_items("Peaches", 17);

?>


This is how we access functions defined in a class: the variable name, followed by an arrow and the function name. The rest, like supplying the parameters, is the usual stuff of function usage.

Now that the items are added, how do we see these items? The following lines achieve this:

<?php

class ShoppingCart {

     var $items;

     function add_items($product_id, $qty)
     {
       $this->items[$product_id]=$qty;
     }

     function show_cart()
     {
       return $this->items;
     }

}

$cart = new ShoppingCart;

$cart->add_items("Apples", 5);
$cart->add_items("Oranges", 15);
$cart->add_items("Peaches", 17);

$cart_items = $cart->show_cart();

foreach($cart_items as $key => $value)
{
     echo "Item name = $key; Item quantity: $value
";
}

?>


After adding the items and getting an array that can be used to display them, we quickly add two more functions to remove the items from the shopping cart, and modify the quantity.

<?php

class ShoppingCart {

     var $items;

     function add_items($product_id, $qty)
     {
       $this->items[$product_id]=$qty;
     }

     function update_items($product_id, $qty)
     {
       if(array_key_exists($product_id, $this->items))
       {
       if($this->items[$product_id]>$qty)
       {
           $this->items[$product_id]-=($this->items[$product_id]-$qty);
       }
       if($this->items[product_id]<$qty)
       {
           $this->items[$product_id]+=abs($this->items[$product_id]-$qty);
       }
       if($qty==0)
       {
           unset($this->items[product_id]);
       }
     }
    }

    function remove_item($product_id)
    {
       if(array_key_exists($product_id, $this->items))
       {
          unset($this->items[$product_id]);
       }
     }

    function show_cart()
    {
       return $this->items;
    }

}

$cart = new ShoppingCart;

$cart->add_items("Apples", 5);
$cart->add_items("Oranges", 15);
$cart->add_items("Peaches", 17);

$cart_items = $cart->show_cart();

foreach($cart_items as $key => $value)
{
echo "Item name = $key; Item quantity: $value <br>";
}

$cart->update_items("Peaches", 28);
$cart->update_items("Oranges", 7);
$cart_items=$cart->show_cart();

echo "================<br>";

foreach($cart_items as $key=>$value)
{
    echo "$key = $value
";
}

$cart->remove_item("Oranges");
$cart_items=$cart->show_cart();

echo "================<br>";

foreach($cart_items as $key=>$value)
{
echo "$key = $value
";
}


?>


The above code performs different tasks with the shopping cart and then displays the result.

This is a very simple example. I hope to write more on classes, especially in PHP, as I need to increase my own repository of re-usable code.

Receive Our Daily Email of Breaking eBusiness News


About the Author:
Amrit Hallan is a freelance copywriter, and a website content writer. He also dabbles with PHP and HTML. For more tips and tricks in PHP, JavaScripting, XML, CSS designing and HTML, visit his blog at http://www.aboutwebdesigning.com

WebProNews RSS Feed

More Articles

Contact WebProNews
Advertisement





TOP NEWS

Targeted Information for Business
WebProNews is part of the iEntry network

Internet Business: Marketing: Small Business:
WebProNews MarketingNewz SmallBusinessNewz
WebProWorld AdvertisingDay PromoteNews
EcommNewz SalesNewz EntrepreneurNewz

Software: Search Engines: Web Design:
WebMasterFree Jayde B2B DesignNewz
NetworkingFiles SearchZA FlashNewz
SecurityConfig SearchNewz WebSiteNotes

Developer: IT Management: Security:
DevWebPro ITManagement SecurityProNews
DevNewz SysAdminNews SecurityConfig
TheDevWeb NetworkingFiles NetworkNewz

The iEntry Network consists of over 100 web publications reaching millions of Internet Professionals. Contact us to advertise.
eBUSINESS RESOURCES






 Advertise | Contact Us | Corporate | Newsletter | Sitemap | Submit an Article | News Feeds
 WebProNews is an iEntry, Inc. ® publication - $line) { echo $line ; } ?> All Rights Reserved
About WebProNews
WebProNews is the number one source for eBusiness News. Over 5 million eBusiness professionals read WebProNews and other iEntry business and tech publications.

WebProNews provides real-time coverage of internet business.

Free Email Newsletters:
WebProNews SearchNewz
WebProWorld DevWebPro
Marketing SecurityNews
Plus over 100 other newsletters!

Send me relevant info on products and services.


WebProWorld
Ten most recent posts.

NetworkingFiles
Featured Software

WebProNews in the News
View all recent mentions of WebProNews from around the world!

Recent Articles On ...
Google eBusiness
Yahoo Ask Jeeves
MSN Blogs
Search Engines Blogging
Affiliate Programs Marketing
eCommerce Advertising
eBay Sun Microsystems
AOL Adsense
Microsoft Adwords
Oracle IBM
Amazon Apple
SEM Mac
SEO iPod
Adsense XBox
PR Adobe



iEntry.com WebProWorld RSS Feed WebProWorld Contact WebProNews Print Version Email a friend Bookmark us