欢迎来到奇迪科技(深圳)有限公司,超值服务提供卓越产品!
网站制作,建设商城、网店常用的购物车类:
session购物车类,代码如下保存为cart.class.php:
<?php class Cart{ static protected $ins; protected $item = array(); final protected function __construct(){} final protected function __clone(){} static protected function Getins(){ if(!(self::$ins instanceof self)){ self::$ins = new self(); } return self::$ins; } public function Getcat(){ if(!($_SESSION['cat']) || !($_SESSION['cat'] instanceof self)){ $_SESSION['cat'] = self::Getins(); } return $_SESSION['cat']; } public function Initem($goods_id){ if($this->Gettype() == 0){ return false; } if(!(array_key_exists($goods_id,$this->item))){ return false; }else{ return $this->item[$goods_id]['num']; } } //购物车加入商品 public function Additem($goods_id,$name,$num,$price){ if($this->Initem($goods_id) != false){ $this->item[$goods_id]['num'] += $num; return; } $this->item[$goods_id] = array(); $this->item[$goods_id]['num'] = $num; $this->item[$goods_id]['name'] = $name; $this->item[$goods_id]['price'] = $price; } //商品数量调整 public function Reduceitem($goods_id,$num){ if($this->Initem($goods_id) == false){ return; } if($num > $this->Getunm($goods_id)){ unset($this->item[$goods_id]); }else{ $this->item[$goods_id]['num'] -=$num; } } //删除单个商品 public function Delitem($goods_id){ if($this->Initem($goods_id)){ unset($this->item[$goods_id]); } } //购物车列表 public function Itemlist(){ return $this->item; } //购物车商品数量 public function Gettype(){ return count($this->item); } //购买某个商品的数量 public function Getunm($goods_id){ return $this->item[$goods_id]['num']; } //商品中总数 public function Getnumber(){ $num = 0; if($this->Gettype() == 0){ return 0; } foreach($this->item as $k=>$v){ $num += $v['num']; } return $num; } //商品价格计算 public function Getprice(){ $price = 0; if($this->Gettype() == 0){ return 0; } foreach($this->item as $k=>$v){ $price += $v['num']*$v['num']; } return $price; } //购物车清空 public function Emptyitem(){ $this->item = array(); } } ?>
以上session购物车代码使用/调用方法举例:
<?php include("cart.class.php"): $cart = new Cart(); $cart = $cart->Getcat(); //添加一个商品到购物车 $cart->Additem('商品ID','商品名称','商品数量','商品价格'); //显示购物车列表 print_r($cart->Itemlist()); ?>
以上代码拿来可以直接使用,对网站制作的朋友有参考价值。
本文版权所有,转载须注明:来源 https://www.qvdv.net/qvdv-oop-81.html