PHP Shopping Cart Code

A simple shopping cart done in PHP

<?php

// if the Cart and Item classes are in separate files, we need these lines:
include_once('cart.php');
include_once('item.php');




// create object to the Cart class
//
$myCart = new Cart();




// create 3 objects to the Item class
// each item has an ID and a NAME that we pass in to Item
//
$item1 = new Item('12345', 'T-Shirt');
$item2 = new Item('AF147Z', 'Polo Shirt');
$item3 = new Item('246810', 'Banana Bread Pan');


// add items to the cart
//
$myCart->addItem($item1);
$myCart->addItem($item2);
$myCart->addItem($item3);



// show what's in the cart
//
$myCart->showCart();



// remove an item
//
$myCart->removeItem($item2->getID());

// show what's in the cart
//
$myCart->showCart();




/**************  CLASSES  **************/


/**** Item class ****/

class Item{

	// class vars
	var $_id;
	var $_name;

	// constructor
	function __construct($id, $name){
		$this->_id = $id;
		$this->_name = $name;
	}

	// getID()
	function getID(){
		return $this->_id;
	}

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

	// showItem()
	function showItem(){
		print "\r\n Item ID: " . $this->_id;
		print "\r\n Name: " . $this->_name;
		print "\r\n";
	}

} // end class Item




/**** Cart class ****/

class Cart {
	// declare some class vars
	var $_cartItems = array();  // array to hold items
	var $_subTotal;             // what does it all cost

	// constructor (empty)
	function __construct() {
	}

	// add an item
	function addItem($item){
		// make item id the key in items array.  easier for unsetting
		$id = $item->getID();
		$this->_cartItems[$id] = $item;

		// print_r($this->_cartItems);
	}

	// remove an item
	function removeItem($id){
		unset( $this->_cartItems[$id] );
	}

	function showCart(){
		// check that we have items
		if ( is_array($this->_cartItems) ){ 
			$cnt = 0;
			foreach( $this->_cartItems as $item ){
				$item->showItem();
				$cnt++;
		  } // end foreach
			print "\r\n You have $cnt items in your cart \r\n";
		}
	}

} // end Cart


?>



/********************  OUTPUT ********************/

 Item ID: 12345
 Name: T-Shirt

 Item ID: AF147Z
 Name: Polo Shirt

 Item ID: 246810
 Name: Banana Bread Pan

 You have 3 items in your cart 

 Item ID: 12345
 Name: T-Shirt

 Item ID: 246810
 Name: Banana Bread Pan

 You have 2 items in your cart