2013-02-25 90 views
0

我應該如何創建一個沒有覆蓋會話/每次反對我的購物車對象?我的下面的代碼無法正常工作,因爲當我每次點擊提交按鈕時,它都會從頭開始並覆蓋購物籃。創建購物車對象

這裏見真人版: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'); 
    ?> 

編輯:我添加了下面的一些購物車類的。我應該提到,當我創建對象並測試它包含在同一個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; 

} 

}

+0

看起來問題出在你的'shoppingCart'類。你可以發佈代碼嗎?或者如果它很長,那麼只需將構造函數和其他方法放入構造函數依賴的類中。 – 2013-02-25 20:39:43

+0

順便說一句,PHP中類的標準約定是它們以大寫字母開頭,例如'類ShoppingCart'而不是'class shoppingCart'。除非你有一個強有力的理由,否則最好遵循這個約定。 – 2013-02-25 20:41:12

回答

0

也許你的會話設置配置錯誤。如果php.ini文件中的會話路徑不正確,則可能是該會議實際上並未被,如果你有錯誤報告設置爲0

檢查你的php.ini會話部分保存。