欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php 购物车类的实现代码(单例模式)

程序员文章站 2022-04-15 13:17:04
...
  1. /**

  2. * php 购物车类
  3. * 单例模式
  4. * Edit bbs.it-home.org
  5. */
  6. class Cart{
  7. static protected $ins; //实例变量
  8. protected $item = array(); //放商品容器
  9. //禁止外部调用

  10. final protected function __construct(){
  11. }
  12. //禁止克隆

  13. final protected function __clone(){
  14. }
  15. //类内部实例化

  16. static protected function Getins(){
  17. if(!(self::$ins instanceof self)){
  18. self::$ins = new self();
  19. }
  20. return self::$ins;

  21. }
  22. //为了能使商品跨页面保存,把对象放入session里

  23. public function Getcat(){
  24. if(!($_SESSION['cat']) || !($_SESSION['cat'] instanceof self)){
  25. $_SESSION['cat'] = self::Getins();
  26. }
  27. return $_SESSION['cat'];

  28. }
  29. //入列时的检验,是否在$item里存在.

  30. public function Initem($goods_id){
  31. if($this->Gettype() == 0){
  32. return false;
  33. }
  34. if(!(array_key_exists($goods_id,$this->item))){
  35. return false;
  36. }else{
  37. return $this->item[$goods_id]['num']; //返回此商品个数
  38. }
  39. }
  40. //添加一个商品

  41. public function Additem($goods_id,$name,$num,$price){
  42. if($this->Initem($goods_id) != false){
  43. $this->item[$goods_id]['num'] += $num;
  44. return;
  45. }
  46. $this->item[$goods_id] = array(); //一个商品为一个数组

  47. $this->item[$goods_id]['num'] = $num; //这一个商品的购买数量
  48. $this->item[$goods_id]['name'] = $name; //商品名字
  49. $this->item[$goods_id]['price'] = $price; //商品单价
  50. }
  51. //减少一个商品

  52. public function Reduceitem($goods_id,$num){
  53. if($this->Initem($goods_id) == false){
  54. return;
  55. }
  56. if($num > $this->Getunm($goods_id)){
  57. unset($this->item[$goods_id]);
  58. }else{
  59. $this->item[$goods_id]['num'] -=$num;
  60. }
  61. }
  62. //去掉一个商品

  63. public function Delitem($goods_id){
  64. if($this->Initem($goods_id)){
  65. unset($this->item[$goods_id]);
  66. }
  67. }
  68. //返回购买商品列表

  69. public function Itemlist(){
  70. return $this->item;
  71. }
  72. //一共有多少种商品

  73. public function Gettype(){
  74. return count($this->item);
  75. }
  76. //获得一种商品的总个数

  77. public function Getunm($goods_id){
  78. return $this->item[$goods_id]['num'];
  79. }
  80. // 查询购物车中有多少个商品

  81. public function Getnumber(){
  82. $num = 0;
  83. if($this->Gettype() == 0){
  84. return 0;
  85. }
  86. foreach($this->item as $k=>$v){

  87. $num += $v['num'];
  88. }
  89. return $num;
  90. }
  91. //计算总价格

  92. public function Getprice(){
  93. $price = 0;
  94. if($this->Gettype() == 0){
  95. return 0;
  96. }
  97. foreach($this->item as $k=>$v){

  98. $price += $v['num']*$v['num'];
  99. }
  100. return $price;
  101. }
  102. //清空购物车

  103. public function Emptyitem(){
  104. $this->item = array();
  105. }
  106. }
  107. ?>
复制代码

调用示例:

  1. include_once('Cart.php');
  2. $cart = Cart::Getcat();
  3. $cart->Additem('1','php学习教程(程序员之家版)','5','9999');
  4. print_r($cart);
  5. ?>
复制代码