-
Notifications
You must be signed in to change notification settings - Fork 0
/
cart.php
51 lines (45 loc) · 1.14 KB
/
cart.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
/**
* Author : Elka
*/
class Cart
{
private $products;
public function __construct()
{
$this->products = [];
}
public function tambahProduk(string $name, int $qty): self
{
if (!isset($this->products[$name])) {
$this->products[$name] = 0;
}
$this->products[$name] += $qty;
return $this;
}
public function hapusProduk(string $name): self
{
if (isset($this->products[$name])) {
unset($this->products[$name]);
}
return $this;
}
public function tampilkanCart()
{
if ($this->products) {
echo '<pre>';
foreach ($this->products as $key => $value) {
echo $key.' ('.$value.')<br/>';
}
}
}
}
$keranjang = new Cart();
$keranjang->tambahProduk("Pisang Hijau", 2);
$keranjang->tambahProduk("Semangka Kuning", 3);
$keranjang->tambahProduk("Apel Merah", 1);
$keranjang->tambahProduk("Apel Merah", 4);
$keranjang->tambahProduk("Apel Merah", 2);
$keranjang->hapusProduk("Semangka Kuning");
$keranjang->hapusProduk("Semangka Merah");
$keranjang->tampilkanCart();