首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 完善購物車類別實作

     編輯:PHP 相關知識

PHP 完善購物車類別實作

封裝 Session 操作,支援加入、移除、修改數量、計算總價、折扣、限量等完整電商購物車功能。

類別結構

class TCart {
    var $SortCount;   // 商品種類數
    var $TotalCost;   // 總金額
    var $Id, $Name, $Price, $Discount, $GoodPrice, $Count, $MaxCount; // 陣列屬性

    function TCart() {
        $this->SortCount = 0;
        session_start();
        foreach (array('sId','sName','sPrice','sDiscount','sGoodPrice','sCount','sMaxCount') as $v)
            session_register($v);
        $this->Update();
        $this->Calculate();
    }

    function Update() { /* 從 Session 同步屬性 */ }
    function Calculate() { /* 依折扣/優惠價計算總價 */ }

    function Add($id, $name, $price, $discount, $goodPrice, $maxCount, $count) { /* 加入/累加 */ }
    function Remove($id) { /* 移除 */ }
    function ModifyCount($index, $count) { /* 修改數量 */ }
    function RemoveAll() { /* 清空 */ }
    function Exists($id) { /* 檢查是否存在 */ }
    function IndexOf($id) { /* 取得索引 */ }
    function Item($i) { /* 取得單項關聯陣列 */ }
    function CartCount() { return $this->SortCount; }
    function GetTotalCost() { return $this->TotalCost; }
}

使用方式

$cart = new TCart();
$cart->Add(101, '商品A', 100, 90, 85, 10, 2); // 9折,優惠價85,限購10,買2件
$cart->ModifyCount(0, 3);
echo "總金額: " . $cart->GetTotalCost();
$cart->RemoveAll();

建構子自動初始化 Session 變數,所有操作即時同步至 Session,適合多頁面購物流程。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved