forked from 20jam/php-oop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterface.php
More file actions
124 lines (101 loc) · 2.53 KB
/
interface.php
File metadata and controls
124 lines (101 loc) · 2.53 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<?php
// Example 1: ---------------------------------------------------------------------------------
// source:
// https://www.php.net/manual/en/language.oop5.interfaces.php
// Context:
// Duck typing
interface CanFly {
public function fly();
}
interface CanSwim {
public function swim();
}
class Bird {
public function info() {
echo "I am a {$this->name}\n";
echo "I am an bird\n";
}
}
// some implementations of birds
class Dove extends Bird implements CanFly {
var $name = "Dove";
public function fly() {
echo "I fly\n";
}
}
class Penguin extends Bird implements CanSwim {
var $name = "Penguin";
public function swim() {
echo "I swim\n";
}
}
class Duck extends Bird implements CanFly, CanSwim {
var $name = "Duck";
public function fly() {
echo "I fly\n";
}
public function swim() {
echo "I swim\n";
}
}
// a simple function to describe a bird
function describe($bird) {
if ($bird instanceof Bird) {
$bird->info();
if ($bird instanceof CanFly) {
$bird->fly();
}
if ($bird instanceof CanSwim) {
$bird->swim();
}
} else {
die("This is not a bird. I cannot describe it.");
}
}
// describe these birds please
describe(new Penguin);
echo "---\n";
describe(new Dove);
echo "---\n";
describe(new Duck);
// Example 2: ---------------------------------------------------------------------------------
// source:
// Context: Webapp
interface WebApp {
public function login($email, $password);
public function register($email, $password, $username);
public function logout();
}
// Website 1
class GoogleCom implements WebApp {
// methods definition
public function login($email, $password) {
echo "Login the user with email: " . $email;
}
public function register($email, $password, $username) {
echo "User registered: Email=" . $email . " and Username= " . $username;
}
public function logout() {
echo "User logged out!";
}
}
/// Another interface
interface CMS {
public function publishPost($post);
}
// Website 2
class MediumCom implements WebApp, CMS {
// methods definition
public function login($email, $password) {
echo "Login the user with email: " . $email;
}
public function register($email, $password, $username) {
echo "User registered: Email=" . $email . " and Username= " . $username;
}
public function logout() {
echo "User logged out!";
}
public function publishPost($post) {
echo $post." published!";
}
}