使用SESSION创建购物车对象


Creating shopping cart object with SESSION

我应该如何在每次都不覆盖会话/对象的情况下创建购物车对象?我下面的代码无法正常工作,因为当我每次单击提交按钮都添加项目时,它会从头开始并覆盖购物篮。

请在此处查看实时版本:http://www.animportantdate.co.uk/home/products.php

我的代码是:

 session_start();
 include('oopCart.php');
 $basket = new shoppingCart($_SESSION['cart']);
 if (isset($_POST['submit'])){
      $id = $_POST['id'];
      $qty = $_POST['qty'];
      $basket->addItem($id, $qty);
 }
 ?>
   <form method="POST" action="products.php">
<input type="hidden" value="dog" name="id">
<input type="hidden" value="10" name="qty">
<input type="submit" value="buy 10 dogs" name="submit">
   </form>
  <?php
  echo '<BR>items in basket: '. $basket->countItems();
  echo '<BR>Total number of dogs (201): '. $basket->numberOfProduct('dog');
  echo '<BR>is dog in basket? '. $basket->isInCart('dog');
  ?>

编辑:我在下面添加了一些shoppingcart类。我应该提到,当我创建对象并测试它包含在同一个php文件中的所有方法时,它工作得很好。因此,这些方法都很有效。只是实例化给我带来了问题。

  class ShoppingCart{
protected $id;
protected $qty;
protected $cart = array();
// constructor accepts the session variable to create cart object
function __construct($cart=""){
   $this->cart = $cart;
}
function addItem($id, $qty=1){
    if (($this->isInCart($id))  == false ){ 
        $this->cart[$id] = array( 'id' => $id, 'qty' => $qty);
    } else{
        $this->cart[$id]['qty'] += $qty;            
    }
}
function isInCart($id){
    $inCart=false;
    if ($this->cart[$id]){
        return $inCart=true;
                break;
    }   
    return $inCart;
}
public function isEmpty(){
    return (empty($this->cart));
}
function countUniqueItems(){
    if ($this->isEmpty()==false){
        foreach($this->cart as $item){
            if($item['id']){
                $uniqueItems++;
            }
        }
    }
    return $uniqueItems;
}

}

也许您的会话设置配置错误。如果php.ini文件中的会话路径不正确,则如果错误报告设置为0,则可能实际上没有保存会话。

请查看php.ini会话部分。