PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 3 ■ OBJECT BASICS

Accessor Methods


Even when client programmers need to work with values held by your class, it is often a good idea to
deny direct access to properties, providing methods instead that relay the needed values. Such methods
are known as accessors or getters and setters.
You have already seen one benefit afforded by accessor methods. You can use an accessor to filter a
property value according to circumstances, as was illustrated with the getPrice() method.
You can also use a setter method to enforce a property type. You have seen that class type hints can
be used to constrain method arguments, but you have no direct control over property types. Remember
the ShopProductWriter class that uses a ShopProduct object to output list data? I can develop this further
so that it writes any number of ShopProduct objects at one time:


class ShopProductWriter {
public $products = array();


public function addProduct( ShopProduct $shopProduct ) {
$this->products[] = $shopProduct;
}


public function write() {
$str = "";
foreach ( $this->products as $shopProduct ) {
$str .= "{$shopProduct->title}: ";
$str .= $shopProduct->getProducer();
$str .= " ({$shopProduct->getPrice()})\n";
}
print $str;
}
}


The ShopProductWriter class is now much more useful. It can hold many ShopProduct objects and
write data for them all in one go. I must trust my client coders to respect the intentions of the class,
though. Despite the fact that I have provided an addProduct() method, I have not prevented
programmers from manipulating the $products property directly. Not only could someone add the
wrong kind of object to the $products array property, but he could even overwrite the entire array and
replace it with a primitive value. I can prevent this by making the $products property private:


class ShopProductWriter {
private $products = array();
//...


It’s now impossible for external code to damage the $products property. All access must be via the
addProduct() method, and the class type hint I use in the method declaration ensures that only
ShopProduct objects can be added to the array property.


The ShopProduct Classes


Let’s close this chapter by amending the ShopProduct class and its children to lock down access control:


class ShopProduct {
private $title;
private $producerMainName;
private $producerFirstName;
protected $price;

Free download pdf