我应该如何创建我的购物车对象而不每次都覆盖会话/对象?我下面的代码无法正常工作,因为当我每次单击提交按钮时添加项目时,它都会从头开始并覆盖购物篮。
在此处查看实时版本: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;
}
}