Low cost ecommerce web development India flash website design
Classes and Objects
// The constructor function
function Page()
{
$this->page = '';
}
Within any method (including the constructor) $this points to the object in
which the method is running. It allows the method to access the other methods
and variables that belong to that particular object. The -> (arrow) operator that
follows $this is used to point at a property or method that's named within the
object.
In the example above, the constructor assigns an empty string value to the $page
member variable we declared at the start. The idea of the $this variable may
seem awkward and confusing to start with, but it's a common strategy employed
by other programming languages, such as Java[5], to allow class members to interact
with each other. You'll get used to it very quickly once you start writing
object oriented PHP code, as it will likely be required for almost every method
your class contains.
Of the other class methods, addHeader and addFooter are almost the same as
before; however, notice that they no longer return values. Instead, they update
the object's $page member variable, which, as you'll see, helps simplify the code
that will use this class. We've also used the addContent method here; with this,
we can add further content to the page (e.g. HTML that we've formatted ourselves,
outside the object). Finally, we have the get method, which is the only method
that returns a value. Once we've finished building the page, we'll use this to create
the HTML.
All these methods access the $page member variable, and this is no coincidence.
The ability to tie PHP code (the methods) to the data (the variables) that it works
on is the most fundamental feature of object oriented programming.
Here's the class in action:
File: 3.php (excerpt)
// Instantiate the Page class
$webPage = new Page();
// Add the header to the page
$webPage->addHeader('A Page Built with an Object');
[5] http://java.sun.com/
website designer freelance ASP PHP ecommerce web developer
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