购物车类实现

class cart {
    static protected $ins = null;
    protected $basket = array();
    
    protected function __construct() {
    }

    static protected function getIns() {
        if(self::$ins == null) {
            self::$ins = new self();
        }

        return self::$ins;
    }

    static public function getCart() {
        // 如果session['cart']不存在,或者存在但不是cart类的实例
        if(!isset($_SESSION['cart']) || !($_SESSION['cart'] instanceof self)) {
            $_SESSION['cart'] = self::getIns();
        }

        return $_SESSION['cart'];
    }

    // 添加商品到购物车
    // 有商品名称,商品id,商品本店价格,购买数量
    public function addItem($id,$name,$shop_price,$num) {
        if(!$this->hasItem($id)) {
            $this->basket[$id] = array('name'=>$name,'shop_price'=>$shop_price,'num'=>$num);
        } else {
            $this->basket[$id]['num'] += $num;
        }
    }

    // 删除商品
    public function delItem($id) {
        if($this->hasItem($id)) {
            unset($this->basket[$id]);
        }
    }

    // 判断某商品是否存在
    public function hasItem($id) {
        return array_key_exists($id,$this->basket);
    }

    // 修改商品数量
    public function modItem($id,$num) {
        if($num == 0) {
            $this->delItem($id);
            return;
        }

        if($this->hasItem($id)) {
            $this->basket[$id]['num'] = $num;
        }
    }

    // 商品加1
    public function incItem($id) {
        if($this->hasItem($id)) {
            $this->basket[$id]['num'] += 1;
        }
    }

    // 商品-1
    public function decItem() {
        if($this->hasItem($id)) {
            $this->basket[$id]['num'] -= 1;
        }
        
        // 要是减到0了,则删掉
        if($this->basket[$id]['num'] == 0) {
            $this->delItem($id);
        }
    }

    // 计算商品种类
    public function cnt() {
        return count($this->basket);
    }
    
    // 返回商品列表
    public function items() {
        return $this->basket;
    }

    // 计算商品的个数
    public function getCount() {
        if($this->cnt() == 0) {
            return 0;
        }

        $count = 0;
        foreach($this->basket as $v) {
            $count += $v['num'];
        }

        return $count;
    }

    // 计算商品的总价格
    public function getPrice() {
        if($this->cnt() == 0) {
            return 0;
        }

        $price = 0;
        foreach($this->basket as $v) {
            $price += $v['num'] * $v['shop_price'];
        }

        return $price;
    }

    // 清空购物车
    public function clear() {
        $this->basket = array();
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值