What are some alternative approaches to managing temporary data like a shopping cart in PHP without constantly creating new instances of the shopCart class?

When managing temporary data like a shopping cart in PHP, one alternative approach is to use sessions to store the cart data. This way, you can access and update the cart data across different pages without constantly creating new instances of the shopCart class. By storing the cart data in the session, you can maintain the state of the cart throughout the user's session on the website.

<?php
session_start();

// Add an item to the shopping cart
if(isset($_POST['add_to_cart'])) {
    $product_id = $_POST['product_id'];
    $quantity = $_POST['quantity'];

    if(isset($_SESSION['cart'][$product_id])) {
        $_SESSION['cart'][$product_id] += $quantity;
    } else {
        $_SESSION['cart'][$product_id] = $quantity;
    }
}

// Remove an item from the shopping cart
if(isset($_POST['remove_from_cart'])) {
    $product_id = $_POST['product_id'];

    if(isset($_SESSION['cart'][$product_id])) {
        unset($_SESSION['cart'][$product_id]);
    }
}

// Display the shopping cart
if(isset($_SESSION['cart'])) {
    foreach($_SESSION['cart'] as $product_id => $quantity) {
        echo "Product ID: $product_id, Quantity: $quantity <br>";
    }
}
?>