-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12-OOP_in_Practice.php
More file actions
92 lines (69 loc) · 1.46 KB
/
12-OOP_in_Practice.php
File metadata and controls
92 lines (69 loc) · 1.46 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
/* This is an example of everything we have learne and how to use OOP in practice. Here we will try making an calculator. */
class Calculator
{
protected $result;
protected $operation;
public function setOperation(OperatorInterface $operation)
{
$this->operation = $operation;
}
public function calculate()
{
foreach(func_get_args() as $number) {
$this->result = $this->operation->run($number, $this->result);
}
}
public function getResult()
{
return $this->result;
}
}
interface OperatorInterface
{
public function run($number, $result);
}
class Adder implements OperatorInterface
{
public function run($number, $result)
{
return $result + $number;
}
}
class Subtractor implements OperatorInterface
{
public function run($number, $result)
{
return $result - $number;
}
}
class Divider implements OperatorInterface
{
public function run($number, $result)
{
return $result / $number;
}
}
class Multiplier implements OperatorInterface
{
public function run($number, $result)
{
return $result * $number;
}
}
// Instantiate
$c = new Calculator;
// Addition
$c->setOperation(new Adder);
$c->calculate(30, 30); // 60
// Subtraction
$c->setOperation(new Subtractor);
$c->calculate(10); // 50
// Division
$c->setOperation(new Divider);
$c->calculate(2); // 25
// Muliplication
$c->setOperation(new Multiplier);
$c->calculate(4); // 100!
// Should give "100"
echo $c->getResult();