<?phpclass Cart{public function Cart() {if(!isset($_SESSION['cart'])){$_SESSION['cart'] = array();}}/*添加商品param int $id 商品主鍵 string $name 商品名稱 float $price 商品價格 int $num 購物數量*/public function addItem($id,$name,$price,$num,$img) {//如果該商品已存在則直接加其數量if (isset($_SESSION['cart'][$id])) {$this->incNum($id,$num);return;}$item = array();$item['id'] = $id;$item['name'] = $name;$item['price'] = $price;$item['num'] = $num;$item['img'] = $img;$_SESSION['cart'][$id] = $item;}/*修改購物車中的商品數量int $id 商品主鍵int $num 某商品修改後的數量,即直接把某商品的數量改為$num*/public function modNum($id,$num=1) {if (!isset($_SESSION['cart'][$id])) {return false;}$_SESSION['cart'][$id]['num'] = $num;}/*商品數量+1*/public function incNum($id,$num=1) {if (isset($_SESSION['cart'][$id])) {$_SESSION['cart'][$id]['num'] += $num;}}/*商品數量-1*/public function decNum($id,$num=1) {if (isset($_SESSION['cart'][$id])) {$_SESSION['cart'][$id]['num'] -= $num;}//如果減少後,數量為0,則把這個商品刪掉if ($_SESSION['cart'][$id]['num'] <1) {$this->delItem($id);}}/*刪除商品*/public function delItem($id) {unset($_SESSION['cart'][$id]);}/*擷取單個商品*/public function getItem($id) {return $_SESSION['cart'][$id];}/*查詢購物車中商品的種類*/public function getCnt() {return count($_SESSION['cart']);}/*查詢購物車中商品的個數*/public function getNum(){if ($this->getCnt() == 0) {//種數為0,個數也為0return 0;}$sum = 0;$data = $_SESSION['cart'];foreach ($data as $item) {$sum += $item['num'];}return $sum;}/*購物車中商品的總金額*/public function getPrice() {//數量為0,價錢為0if ($this->getCnt() == 0) {return 0;}$price = 0.00;foreach ($this->items as $item) {$price += $item['num'] * $item['price'];}return sprintf("%01.2f", $price);}/*清空購物車*/public function clear() {$_SESSION['cart'] = array();}}