/
class-with-traits.php
87 lines (86 loc) · 2.32 KB
/
class-with-traits.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
82
83
84
85
86
87
<?php
trait Nameable {
public $first_name = null;
public $last_name = null;
public function get_name() {
return $this->first_name . " " . $this->last_name;
}
public function set_name($name) {
$split_name = explode(" ", $name, 2);
$length = count($split_name);
$rv = true;
if ($length === 0) {
$rv = false;
}
elseif ($length === 1) {
$this->first_name = $this->last_name = $split_name[0];
}
else {
$this->first_name = $split_name[0];
$this->last_name = $split_name[1];
}
return $rv;
}
}
class Contact {
use Nameable;
public $phone_number;
public function __construct($first_name = null, $last_name = null) {
$this->first_name = $first_name;
$this->last_name = $last_name;
}
public function __toString() {
$s = "";
if ($this->first_name) {
$s .= $this->first_name;
}
if ($this->last_name) {
if (count($s) > 0) {
$s .= " ";
}
$s.= $this->last_name;
}
if ($this->phone_number) {
if (count($s) > 0) {
$s .= ": ";
}
else {
$s .= "Someone's Phone Number: ";
}
$s .= $this->phone_number;
}
return $s;
}
}
?>
<!doctype html>
<html>
<head>
<title>Object Oriented Programming - Class with Interface</title>
</head>
<body>
<strong>A Simple Class, Empty Constructor, Two Names</strong>
<br>
<?php
$john23 = new Contact();
$john23->set_name("Angelo Roncalli");
$john23->phone_number = "777-777-7777";
?>
<p><?php print $john23 ?></p>
<strong>A Simple Class, Empty Constructor, Three Names</strong>
<br>
<?php
$john23 = new Contact();
$john23->set_name("Angelo Giuseppe Roncalli");
$john23->phone_number = "777-777-7777";
?>
<p><?php print $john23 ?></p>
<strong>A Simple Class, Parameterized Constructor</strong>
<br>
<?php
$john23 = new Contact("Angelo", "Roncalli");
$john23->phone_number = "777-777-7777";
?>
<p><?php print $john23 ?></p>
</body>
</html>