/
inheritance.php
81 lines (61 loc) · 1.77 KB
/
inheritance.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
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
<?php
require_once('person.php');
// Student and tutor both inherit from Person
class Student extends Person {
private $grades = array();
public function Student($name, $grade_ary) {
$this->setFName($name);
$this->grades = $grade_ary;
}
public function setGrades($grade_ary) {
$this->grades = $grade_ary;
}
// Polymorphic function changes what
// setFirstName does for Student without
// affecting how Person works
public function setFirstName($name) {
$this->setFName($name);
}
private function setFName($name) {
$this->fname = $name . ' (' . get_class($this) . ')';
}
}
class Tutor extends Person {
private $classes = array();
public function Tutor($name, $class_ary) {
$this->setFName($name);
$this->classes = $class_ary;
}
public function setFirstName($name) {
$this->setFName($name);
}
public function getClasses() {
return $this->classes;
}
private function setFName($name) {
$this->fname = $name . ' - ' . get_class($this);
}
}
// Prove the polymorphism by calling a member function
function setName(Person $person, $name) {
$person->setFirstName($name);
}
function showDetail(Person $person) {
$name = $person->getFirstName();
return "This person's name is $name";
}
// Test the inheritance/polymorphism
$s1 = new Student('Dave', array('English' => 74,
'Maths' => 46,
'Science' => 65));
$t1 = new Tutor('Mike', array('Maths', 'Science'));
$t2 = new Tutor('Chris', array('English', 'History'));
setName($s1, 'Peter');
setName($t2, 'Mike');
echo '<br />';
echo showDetail($s1);
echo '<br />';
echo showDetail($t1);
echo '<br />';
echo showDetail($t2);
?>