What are the advantages of using a class-based approach for implementing shopping cart functionality in PHP?
Using a class-based approach for implementing shopping cart functionality in PHP allows for better organization, reusability, and maintainability of code. It also provides a clear structure for managing cart items, calculating totals, and applying discounts or promotions.
class ShoppingCart {
private $items = [];
public function addItem($product, $quantity) {
if(isset($this->items[$product])) {
$this->items[$product] += $quantity;
} else {
$this->items[$product] = $quantity;
}
}
public function removeItem($product) {
unset($this->items[$product]);
}
public function getTotal() {
$total = 0;
foreach($this->items as $product => $quantity) {
// Calculate total based on product price and quantity
}
return $total;
}
}