Specifications

With only a single access point, we can implement checks to make sure that only sensible data
is being stored. If it occurs to us later that the value of $attribute should only be between
zero and one hundred, we can add a few lines of code once and check before allowing
changes. Our set_attribute() function could be changed to look as follows:
function set_attribute($new_value)
{
if( $new_value >= 0 && $newvalue <= 100 )
$this->attribute = $new_value;
}
This change is trivial, but had we not used an accessor function, we would have to search
through every line of code and modify every access to $attribute, a tedious and error-prone
exercise.
With only a single access point, we are free to change the underlying implementation. If for
some reason, we choose to change the way $attribute is stored, accessor functions allow us
to do this and only change the code in one place.
We might decide that rather than storing $attribute as a variable, we will only retrieve it
from a database when needed, calculate an up-to-date value every time it is requested, infer a
value from the values of other attributes, or encode our data as a smaller data type. Whatever
change we decide to make, we can simply modify our accessor functions. Other sections of
code will not be affected as long as we make the accessor functions still accept or return the
data that other parts of the program expect.
Calling Class Operations
We can call class operations in much the same way that we call class attributes. If we have the
following class:
class classname
{
function operation1()
{
}
function operation2($param1, $param2)
{
}
}
and create a object of type classname called $a as follows:
$a = new classname();
Using PHP
P
ART I
154
08 7842 CH06 3/6/01 3:34 PM Page 154