Hi all, I’ve written a shopping cart class but seems to be having a couple of problems with it. See below for the class:
<?php
class ShoppingCart {
protected $items = array();
public function is_empty(){
if(empty($this->items)):
return true;
else:
return false;
endif;
}
//Method for adding an item to the cart...
public function add_items($id, $info){
//Is it already in the cart?
if(isset($this->items[$id])):
//Call the update_item() method:
$this->update_item($id, $this->items[$id]['qty']+1);
else:
//Add the array of info...
$this->items[$id] = $info;
//Add the quantity...
$this->items[$id]['qty'] = 1;
//Print a message...
echo "Item has been added successfully!";
endif;
}
public function update_item($id, $qty){
//Delete if quantity equals 0...
if($qty == 0):
$this->delete_item($id);
elseif(($qty > 0) && ($qty != $this->items[$id]['qty'])):
//Update the quantity...
$this->items[$id]['qty'] = $qty;
//Print a message...
echo "You have now $qty of your chosen product.";
endif;
}
//Method for deleteing an item...
public function delete_items($id){
//Confirm this isn't in the cart...
if(isset($this->items[$id])):
echo "This item has now been removed from your cart!";
//Remove the item...
unset($this->items[$id]);
endif;
}
}
?>
I then use the class in the following way, I’ve already included the class and created a new object:
//Section to add an item to the cart!
if(isset($_POST['cartadd'])):
$bag->add_items($_POST['prodId'], "Hello");
$_SESSION['cart'] = serialize($bag);
endif;
Then when I do the following the following is produced:
print_r(unserialize($_SESSION['cart']));
ShoppingCart Object ( [items:protected] => Array ( [368] => 2ello [19] => 1ello ) )
Any ideas why the ‘H’ is missing? Any help/advice is appreciated