I have a 'view basket' page that allows users to change the quantities in the cart - this works fine, so a bit confused why I can't get the first bit working.
My class is as follows:
Code: Select all
class ShoppingCart
{
// collection of items placed in the shopping cart
private $items;
// initialize a ShoppingCart object
public function __construct()
{
$this->items = array();
}
// expose read-only convenience properties
public function __get($value)
{
switch ($value)
{
// contents - returns the entire contents of the cart
case 'contents':
return $this->items;
brake;
// isEmpty - returns whether or not the cart is empty
case 'isEmpty':
return (count($this->items) == 0);
break;
// totalItems - returns the total number of distinct items
// in the cart
case 'totalItems':
return count($this->items);
break;
// totalQty - returns the total quantity of items in the cart
case 'totalQty':
return array_sum($this->items);
break;
}
}
// add an item to the shopping cart
public function addItem($item, $qty)
{
if (!$qty)
{
$this->removeItem($item);
}
else
{
if (!in_array($item,$this->items)) {
$this->items[$item] = $qty;
} else {
[b] $currentqty= $this->items[$item];[/b]
[b] $newqty = $currentqty + 1;[/b]
[b] $this->items[$item] = $newqty;[/b]
}
}
}
// returns an item's quantity in the cart
public function qtyItem($item)
{
if (!isset($this->items[$item]))
{
return 0;
}
else
{
return $this->items[$item];
}
}
}Code: Select all
// add item to cart
if (isset($_GET['add']))
{
if(isset($_GET['qty'])) {
$cart->addItem($item, $_GET['qty']);
}
else {
$cart->addItem($item);
}
}Code: Select all
// update item quantities in shopping cart
if (isset($_GET['update']))
{
foreach ($_POST['qty'] as $item => $qty)
{
$cart->addItem($item, $qty);
}
}I thought I could just change the addItem method in the class itself, I've done a check to see if the item already exists (if so just add it as normal) and this seems to work, as falls through to the 'else if' it does already exist, but I can't seem to increase the quantity- it stays at 1! I've highlighted the code in the class code section that isn't working.
Sorry for this very long post, but if anyone has any ideas would be grateful as struggling to really understand whats going on here.
Thanks!
Stef