class _cart
{
private $_contents = array();
private $_created;
/**
* The class constructor
*
*/
public function __construct() {
$this->_created = time();
}
/**
* Add a product to the cart
* @access public
* @param $productID integer
*
*/
public function add_item($productID) {
if (isset($this->_contents[$productID])) {
$this->_contents[$productID]++;
} else {
$this->_contents[$productID] = 1;
}
//print_r($this->_contents);
}
/**
* Remove product from cart
* @access public
* @param $productId integer
*
*/
public function delete_item($productID) {
if (isset($this->_contents[$productID])) {
unset($this->_contents[$productID]);
}
}
/**
* Change the quantity of a particular item held in the shopping cart
*
* @access public
* @param integer $productID
* @param integer $quantity
*/
public function update_quantity($productID, $quantity) {
$this->_contents[$productID] = $quantity;
}
/**
* Get all items currently in cart
*
* @access public
* @return unknown
*/
public function get_items() {
return $this->_contents;
}
/**
* How many items are in the user's cart?
*
* @access public
* @return INTEGER
*
*/
public function count_items() {
return array_sum($this->_contents);
}
/**
* Calculate the cost of all items in the cart
* @access public
* @return float
*
*/
public function calculate_cost()
{
$cost = 0.00;
foreach($this->_contents AS $id => $quantity) {
$product = new _product($id);
$cost = $cost + ($product -> price * $quantity);
}
return number_format($cost, 2);
}
}
I have tested the methods in the cart class above which I got it from the link here,
http://www.easyphpwebsites.com/blog/read/Easy-Object-Oriented-Programming-with-PHP
But the method of calculate_cost() requires another class - _product class I think!??
Any one know how to create this product class?
I tried to imagine how this _product class is like, so this is my version,
class _store
{
function get_store()
{
return new SimpleXMLElement(file_get_contents(STORE_XML));
}
}
class _product
{
public $_product_id = null;
public function __construct($id)
{
$this->_product_id = $id;
}
public function get_price()
{
$object_store = new _store();
$store = $object_store -> get_store();
foreach ($store as $product)
{
if ($product -> id == $this->_product_id)
{
return $product -> price;
}
}
}
}
however, to use this _product class the version of mine, will require to change the calculate_cost() into this below which I think it is not looking good at all as it needs a few more lines… and I don’t think my _prodcut class is looking great!
public function calculate_cost()
{
$cost = 0.00;
foreach($this->_contents AS $id => $quantity) {
$product = new _product($id);
$cost_string = $product -> get_price();
$cost_float = "$cost_string" + 0;
$cost = $cost + ($cost_float * $quantity);
}
return number_format($cost, 2);
}
Many thanks,
Lau