w3resource

PHP OOP: Shopping cart class


17. ShoppingCart Class

Write a PHP class called 'ShoppingCart' with properties like 'items' and 'total'. Implement methods to add items to the cart and calculate the total cost.

Sample Solution:

PHP Code :

<?php
class ShoppingCart {
    private $items;
    private $total;

    public function __construct() {
        $this->items = [];
        $this->total = 0;
    }

    public function addItem($item, $price) {
        $this->items[$item] = $price;
        $this->total += $price;
    }

    public function getTotal() {
        return $this->total;
    }
}

$cart = new ShoppingCart();

$cart->addItem("Product 1", 20);
$cart->addItem("Product 2", 30);
$cart->addItem("Product 3", 10);

$total = $cart->getTotal();
echo "Total cost: $" . $total;

?>

Sample Output:

Total cost: $60

Explanation:

In the above exercise -

  • The "ShoppingCart" class has two private properties: $items and $total. $items is an associative array that stores the items in the cart as keys and their corresponding prices as values. $total keeps track of the total cost of all items in the cart.
  • The constructor method __construct() initializes the $items array as an empty array and sets the $total to 0.
  • The addItem($item, $price) method takes $item and its corresponding $price as parameters. It adds the item and its price to the $items array and increments the $total by the price.
  • The getTotal() method retrieves the total cost of the items in the cart.

Flowchart:

Flowchart: Shopping cart class.

For more Practice: Solve these Related Problems:

  • Write a PHP class ShoppingCart that maintains a list of items and includes methods to add items and compute the total cost with tax.
  • Write a PHP script to simulate a shopping cart with dynamic item additions and then calculate and display the total price.
  • Write a PHP function to remove an item from the ShoppingCart by its index and then update the total cost accordingly.
  • Write a PHP program to implement discount calculation in the ShoppingCart class that adjusts the total based on item count.

Go to:


PREV : Calculator Class with Private Result.
NEXT : Logger with Singleton Design Pattern.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.