php 购物车类的实现代码(单例模式)
php中文网
发布时间:2016-07-25 08:59:33
|
910人浏览过
|
来源于php中文网
原创
-
-
/**
- * php 购物车类
- * 单例模式
- * edit bbs.it-home.org
- */
- 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;
- }
立即学习“PHP免费学习笔记(深入)”;
//为了能使商品跨页面保存,把对象放入session里
- public function Getcat(){
- if(!($_SESSION['cat']) || !($_SESSION['cat'] instanceof self)){
- $_SESSION['cat'] = self::Getins();
- }
return $_SESSION['cat'];
- }
//入列时的检验,是否在$item里存在.
- 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; //商品单价
- }
//减少一个商品
Shoping购物网源码
该系统采用多层模式开发,这个网站主要展示女装的经营,更易于网站的扩展和后期的维护,同时也根据常用的SQL注入手段做出相应的防御以提高网站的安全性,本网站实现了购物车,产品订单管理,产品展示,等等,后台实现了动态权限的管理,客户管理,订单管理以及商品管理等等,前台页面设计精致,后台便于操作等。实现了无限子类的添加,实现了动态权限的管理,支持一下一个人做的辛苦
下载
- 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();
- }
- }
- ?>
-
复制代码
调用示例:
-
-
include_once('Cart.php');
- $cart = Cart::Getcat();
- $cart->Additem('1','php学习教程(程序员之家版)','5','9999');
- print_r($cart);
- ?>
复制代码
|
PHP速学教程(入门到精通)
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
下载
本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn