Shopping Cart with an Array in Session

A

Anonymous

Guest
I'm new to PHP and I'm trying to create a shopping cart using a class.

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"];
 
I'm not sure if this is it or not, but are you starting a session on the other page? I think for every page you access sessions on, you will need session_start(); I haven't used sessions much myself, so I'm not positive that would be the problem you are having, but it's something to check out.

Good luck
 
Yes, I call start_session(); on the pages where I'm trying to access the $cart.
 
Does anyone know why I loose the data in my array in the cart class when I get it back from a session?
 
I found my problem. I was getting a copy of my $cart and not a reference to it.
Code:
//I was doing this. Getting a copy of cart
$cart = $_SESSION["cart"];

//I should have been doing this. Getting a reference of cart
$cart = & $_SESSION["cart"];
 
Back
Top