Chapter 2
[ 21 ]
Accessing Properties and Methods from
Inside the Class
Are you wondering how a function can access the class properties from inside its
content? Let's see using the following code:
public function setBody($body)
{
$this->body = $body;
}
There is a private property named $body inside our class, and if we want to access
it from within the function, we must refer to it with $this. $this means a reference
to current instance of this object. So we can access the body property with
$this->body. Please note that we have to access the properties (i.e class variables)
of a class using a "->" following the instance.
Similarly, like properties, we can access any member method from inside another
member method in this format. For example, we can evoke setSubject method as
$this->setSubject().
Please note that $this keyword is only valid inside the scope of a method,
as long as it is not declared as static. You can not use $this keyword
from outside the class. We will learn about this "static", "private", "public"
keywords more in the Modifiers section later this chapter.
Using an Object
Let's use the newly created Emailer object from inside our PHP code.
Pages:
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