A
Anonymous
Guest
I'm new to PHP and I'm trying to create a shopping cart using a class.
Right now, I can add items to my cart and display the values in the $cart->items.
My problem is if I put my $cart in the $_SESSION, when I try to access it again in another page, it gets the $cart, but the $cart->items is empty.
Code:
class Item {
var $id;
var $quantity;
var $description;
var $price;
function Item($i = 0, $q = 0, $d = "", $p = 0) {
$this->id = $i;
$this->quantity = $q;
$this->description = $d;
$this->price = $p;
}
}
class Cart {
var $items = array();
function addItem($item) {
if (isset($this->items[$item->id])) {
$this->items[$item->id]->quantity += $item->quantity;
} else {
$this->items[$item->id] = $item;
}
}
}
Right now, I can add items to my cart and display the values in the $cart->items.
My problem is if I put my $cart in the $_SESSION, when I try to access it again in another page, it gets the $cart, but the $cart->items is empty.
Code:
if (!isset($_SESSION["cart"])) {
echo("Creating new cart");
$_SESSION["cart"] = new Cart();
}
$cart = $_SESSION["cart"];