What is the purpose of the class for handling shopping cart functionality in PHP?
The purpose of the class for handling shopping cart functionality in PHP is to create a reusable and organized way to manage the items that a user has added to their shopping cart while browsing an online store. This class typically includes methods for adding items to the cart, removing items from the cart, updating quantities, calculating totals, and displaying the contents of the cart.
<?php
class ShoppingCart {
private $items = array();
public function addItem($product_id, $quantity, $price) {
$this->items[$product_id] = array(
'quantity' => $quantity,
'price' => $price
);
}
public function removeItem($product_id) {
unset($this->items[$product_id]);
}
public function updateQuantity($product_id, $quantity) {
$this->items[$product_id]['quantity'] = $quantity;
}
public function calculateTotal() {
$total = 0;
foreach ($this->items as $item) {
$total += $item['price'] * $item['quantity'];
}
return $total;
}
public function displayCart() {
foreach ($this->items as $product_id => $item) {
echo "Product ID: $product_id | Quantity: {$item['quantity']} | Price: {$item['price']} <br>";
}
}
}
?>
Keywords
Related Questions
- What are some best practices for inserting data into a MySQL database table using PHP?
- Are there specific steps to take when upgrading or switching PHP versions to avoid issues like the memory_limit being ignored?
- What are the potential pitfalls of using pre-built PHP scripts for developing a web portal, and are there any best practices to follow when customizing them?