Maison > Article > développement back-end > PHP购物车类代码
PHP购物车类代码
在开发网络购物网站的时候,购物车类是购物网站的必备模块。总结一个php实现购物车类。实现了购物车中的商品的添加,修改,删除,列表,以及各种计算的相关功能。采用了php单一类的原理,安全高效,简单易扩展。
class Cart{<br /> static protected $ins; //实例变量<br /> protected $item=array(); //放商品容器<br /> //禁止外部调用<br /> final protected function __construct(){}<br /> //禁止克隆<br /> final protected function __clone(){}<br /> //类内部实例化<br /> static protected function Getins(){<br /> if(!(self::$ins instanceof self)){self::$ins=new self();}return self::$ins;<br /> }<br /> //为了能使商品跨页面保存,把对象放入session里<br /> public function Getcat(){<br /> if(!isset($_SESSION['cat'])||!($_SESSION['cat'] instanceof self)){<br /> $_SESSION['cat']=self::Getins();<br /> }<br /> return $_SESSION['cat'];<br /> }<br /> //入列时的检验,是否在$item里存在<br /> public function Initem($goods_id){<br /> if($this->Gettype()==0){<br /> return false;<br /> }<br /> //这里检验商品是否相同是通过goods_id来检测,并未通过商品名称name来检测,具体情况可做修改<br /> if(!(array_key_exists($goods_id,$this->item))){<br /> return false;<br /> }else{<br /> return $this->item[$goods_id]['num']; //返回此商品个数<br /> }<br /> }<br /> //添加一个商品<br /> public function Additem($goods_id,$name,$num,$price){<br /> if($this->Initem($goods_id)!=false){<br /> $this->item[$goods_id]['num']+=$num;<br /> return;<br /> }<br /> $this->item[$goods_id]=array(); //一个商品为一个数组<br /> $this->item[$goods_id]['num']=$num; //这一个商品的购买数量<br /> $this->item[$goods_id]['name']=$name; //商品名字<br /> $this->item[$goods_id]['price']=$price; //商品单价<br /> }<br /> //减少一个商品<br /> public function Reduceitem($goods_id,$num){<br /> if($this->Initem($goods_id)==false){<br /> return;<br /> }<br /> if($num>$this->Getunm($goods_id)){<br /> unset($this->item[$goods_id]);<br /> }else{<br /> $this->item[$goods_id]['num']-=$num;<br /> }<br /> }<br /> //去掉一个商品<br /> public function Delitem($goods_id){<br /> if($this->Initem($goods_id)){<br /> unset($this->item[$goods_id]);<br /> }<br /> }<br /> //返回购买商品列表<br /> public function Itemlist(){<br /> return $this->item;<br /> }<br /> //一共有多少种商品<br /> public function Gettype(){<br /> return count($this->item);<br /> }<br /> //获得一种商品的总个数<br /> public function Getunm($goods_id){<br /> return $this->item[$goods_id]['num'];<br /> }<br /> // 查询购物车中有多少个商品<br /> public function Getnumber(){<br /> $num=0;<br /> if($this->Gettype()==0){<br /> return 0;<br /> }<br /> foreach($this->item as $k=>$v){<br /> $num+=$v['num'];<br /> }<br /> return $num;<br /> }<br /> //计算总价格<br /> public function Getprice(){<br /> $price=0;<br /> if($this->Gettype()==0){<br /> return 0;<br /> }<br /> foreach($this->item as $k=>$v){<br /> $price+=$v['num']*$v['num'];<br /> }<br /> return $price;<br /> }<br /> //清空购物车<br /> public function Emptyitem(){<br /> $this->item=array();<br /> }<br />}
以上购物车类的调用示例如下:
<?php<br />header("Content-type:text/html;charset=utf-8");<br />session_start();<br />$cart = Cart::Getcat();<br />$cart->Additem('1','www.phpernote.com','1','1亿');<br />$cart->Additem('2','php购物车类','3','10');<br />print_r($cart);