Specifications
$this->attribute = $param
echo $this->attribute;
}
}
Some programming languages allow you to limit access to attributes by declaring such data
private or protected. This feature is not supported by PHP, so all your attributes and operations
are visible outside the class (that is, they are all public).
We can perform the same task as previously demonstrated from outside the class, using
slightly different syntax.
class classname
{
var $attribute;
}
$a = new classname();
$a->attribute = “value”;
echo $a->attribute;
It is not a good idea to directly access attributes from outside a class. One of the advantages of
an object-oriented approach is that it encourages encapsulation. Although you cannot enforce
data hiding in PHP, with a little willpower, you can achieve the same advantages.
If rather than accessing the attributes of a class directly, you write accessor functions, you can
make all your accesses through a single section of code. When you initially write your acces-
sor functions, they might look as follows:
class classname
{
var $attribute;
function get_attribute()
{
return $this->attribute;
}
function set_attribute($new_value)
{
$this->attribute = $new_value;
}
}
This code simply provides functions to access the attribute named $attribute. We have a
function named get_attribute() which simply returns the value of $attribute, and a func-
tion named
set_attribute() which assigns a new value to $attribute.
At first glance, this code might seem to add little or no value. In its present form this is proba-
bly true, but the reason for providing accessor functions is simple: We will then have only one
section of code that accesses that particular attribute.
Object-Oriented PHP
C
HAPTER 6
6
OBJECT-ORIENTED
PHP
153
08 7842 CH06 3/6/01 3:34 PM Page 153