How can object-oriented programming principles be applied to improve the structure and functionality of PHP scripts handling shopping cart functionality?
Object-oriented programming principles can be applied to improve the structure and functionality of PHP scripts handling shopping cart functionality by creating classes for items, cart, and user, and using inheritance and encapsulation to organize and manage the code more efficiently. By creating separate classes for each component of the shopping cart, it becomes easier to add new features, modify existing ones, and maintain the codebase.
class Item {
private $name;
private $price;
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
public function getName() {
return $this->name;
}
public function getPrice() {
return $this->price;
}
}
class Cart {
private $items = [];
public function addItem(Item $item) {
$this->items[] = $item;
}
public function getTotalPrice() {
$total = 0;
foreach ($this->items as $item) {
$total += $item->getPrice();
}
return $total;
}
}
$item1 = new Item('Product 1', 10.00);
$item2 = new Item('Product 2', 20.00);
$cart = new Cart();
$cart->addItem($item1);
$cart->addItem($item2);
echo 'Total price: $' . $cart->getTotalPrice();
Related questions
-
PHP form submissions special characters
-
streaming responses PHP developers
-
PHP checkboxes while loop