php购物车类的实现代码与应用举例
时间:2021-07-01 10:21:17
帮助过:19人阅读
- class Shopcar
- {
- //商品列表
- public $productList=array();
- /**
- *
- * @param unknown_type $product 传进来的商品
- * @return true 购物车里面没有该商品
- */
- public function checkProduct($product)
- {
- for($i=0;$iproductList);$i++ )
- {
- if($this->productList[$i]['name']==$product['name'])
- return $i;
- }
- return -1;
- }
- //添加到购物车
- public function add($product)
- {
- $i=$this->checkProduct($product);
- if($i==-1)
- array_push($this->productList,$product);
- else
- $this->productList[$i]['num']+=$product['num'];
- }
- //删除
- public function delete($product)
- {
- $i=$this->checkProduct($product);
- if($i!=-1)
- array_splice($this->productList,$i,1);
- }
- //返回所有的商品的信息
- public function show()
- {
- return $this->productList;
- }
- }
2、productList.html
- php购物车-商品列表页面-bbs.it-home.org
3、index.php
- require 'Shopcar.class.php';
- session_start();
- $name=$_POST['name'];
- $num=$_POST['num'];
- $price=$_POST['price'];
- $product=array('name'=>$name,'num'=>$num,'price'=>$price);
- print_r($product);
- if(isset($_SESSION['shopcar']))
- $shopcar=unserialize($_SESSION['shopcar']);
- else
- $shopcar=new Shopcar();
- $shopcar->add($product);
- $_SESSION['shopcar']=serialize($shopcar);
- ?>
4、show.php
- 商品信息展示页_bbs.it-home.org
|