- $_SESSION is just an array.
- An array is being stored in $_SESSION['cart'].
- You seem to be overwriting that array, with only the newly added item.
As an example, this code:
if (isset($_POST['submit']))
{
$cart= new Cart();
$cart->add($_POST['id'],2);
$item= $cart->getCart();
$_SESSION["cart"]=$cart;
}
can be changed to:
if (isset($_POST['submit']))
{
$_SESSION["cart"][$_POST['id']] = 2;
}
Now, it'll simply add to the array stored in $_SESSION['cart']. Notice, that it doesn't use the cart at all.
Try:
if (isset($_POST['submit']))
{
$cart= new Cart($_SESSION["cart"]); // this should bring in the previous items
$cart->add($_POST['id'],2); // what is this magic number '2'? Quantity? But where is it from?
$_SESSION["cart"] = $cart->getCart();
}
Edit: Some more explanation.
The cart class' constructor accepts a parameter that it stores internally:
private $cart;
function __construct($cart="") {
$this->cart = $cart;
}
In all honestly, this should be a bit more intelligent:
private $cart;
function __construct($cart = array()) {
if (is_array($cart))
{
$this->cart = $cart;
}
else
{
// maybe print some error, informing the developer that he's using the cart class incorrectly
// or better yet, trigger a PHP warning:
trigger_error('Cart class constructor expects an array parameter', E_USER_WARNING);
}
}
This change guards against providing anything but an array to the constructor. Note, that it can still be given an array that the class doesn't understand, e.g. a multidimensional array. In that situation, the cart class won't destroy existing data in the array, unless an item id matches one of the keys in the original array.