<?php
/*
购物车类
*/
// session_start();
class Cart
{
//定义一个数组来保存购物车商品
private $iteams;
private static $ins=null;
final protected function __construct()
{
if(isset($_session['cart']))
{
$this->$iteams=session('cart');
}else
{
$this->iteams=array();
}
}
/*防克隆*/
final protected function __clone(){}
/*单列模式调用此类*/
public static function getins()
{
if(self::$ins==null)
{
self::$ins=new self();
}
return self::$ins;
}
/*添加商品*/
public function add($goods_id,$goods_name,$shop_price)
{
if(!isset($this->iteams[$goods_id]))
{
$row=array();
$row['goods_name']=$goods_name;
$row['shop_price']=$shop_price;
$row['num']=1;
$this->iteams[$goods_id]=$row;
}else
{
$this->iteams[$goods_id]['num']+=1;
}
return $this->iteams;
}
/*删除商品*/
public function del($goods_id)
{
unset($this->iteams[$goods_id]);
}
/*减少一件商品数量*/
public function _num($goods_id)
{
if(isset($this->iteams[$goods_id]))
{
$this->iteams[$goods_id]['num']-=1;
if($this->iteams[$goods_id]['num']==0)
{
$this->del($goods_id);
}
}
}
/*计算商品总价格*/
public function total_price()
{
$money=0.0;
foreach($this->iteams as $v)
{
$money+=$v['shop_price']*$v['num'];
}
return $money;
}
/**计算商品总数量(有多少种商品)*/
public function shop_num()
{
return count($this->iteams);
}
/*列出所有商品*/
public function lists_shop()
{
return $this->iteams;
}
/*清空购物车*/
public function clear_cart()
{
$this->iteams=array();
}
/*session destory destruct 析构函数*/
public function __destruct()
{
$_session['cart']=$this->iteams;
}
}
$g=Cart::getins();
$g->add('1','sanxing',55);
$g->add('2','nokio',33.9);
$money=$g->total_price();
print_r($money);
echo '<br/>';
print_r($g->shop_num());
echo '<br/>';
print_r($g->lists_shop());
?>