-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02.php
executable file
·48 lines (43 loc) · 1.3 KB
/
02.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
<?php
class VendingMachine
{
private $items = [
"A" => 5000,
"B" => 7000,
"C" => 3000
];
private $coinsInserted = 0;
public function isItemAvailable($item)
{
return array_key_exists($item, $this->items) && $this->items[$item] > 0;
}
public function insertCoin($mount)
{
return $this->coinsInserted += $mount;
}
public function dispenseItem($itemName)
{
if ($this->isItemAvailable($itemName)) {
if ($this->coinsInserted >= $this->items[$itemName]) {
$this->coinsInserted -= $this->items[$itemName];
return [
'itemName' => $itemName,
'price' => $this->items[$itemName],
'change' => $this->coinsInserted
];
} else {
echo 'Not enough coins.';
}
}
}
}
$vendingMachine = new VendingMachine();
echo 'Insert your coin:';
$amount = trim(fgets(fopen("php://stdin", "r")));
$vendingMachine->insertCoin($amount);
echo 'choose your item:';
$itemName = trim(fgets(fopen("php://stdin", "r")));
$result = $vendingMachine->dispenseItem($itemName);
if (is_array($result)) {
echo 'Your item is ' . $result['itemName'] . ' and change: ' . $result['change'] . ' coin.';
}