[ Team LiB ] Previous Section Next Section

Limiting Access to Object Methods

A principle of object-oriented code is that you should only expose as much of a class as you absolutely have to. Objects should have clearly defined responsibilities and clear public interfaces. You might want to create all sorts of utility methods for a function. Unless they are useful to client code, and part of the class's core responsibility, you should hide them from the wider world. Let's say, for example, that we would like to delegate the creation of the $productString property in Listing 9.5 to a method.

Currently, all work takes place in the setName() method:


function setName( $n ) {
  $this->name = $n;
  $this->productString = $this->name." ".$this->code;
}

Because the mechanism for creating product strings might become more complex, and because other methods might want to reset the string themselves for various reasons, we extract the line that assigns to the $productString property, replacing it with a call to a new method:


function setName( $n ) {
  $this->name = $n;
  $this->makeProductString( $n, $this->code );
}
function makeProductString( $string, $code) {
  return $this->productString = "$string $code";
}

Of course, we've now made trouble for ourselves because client code can access the makeProductString() method and mess with our data. We want the object and only the object to construct this property. In PHP 5, we can apply privacy to methods just as we can to properties:


private function makeProductString( $string, $code) {
  // ...

The makeProductString() function is now accessible only by methods in the Item class. You can apply three possible privacy keywords to method declarations. public is the default and is implicit. A method declared with the public keyword (or with no privacy keyword at all) is accessible from any context. Methods declared private are accessible only to other methods in the enclosing class. Methods declared with the protected keyword are available only to the enclosing class and any child classes that extend the closing class. Once again, we will cover child classes in the section "Inheritance," later in this chapter.

graphics/watchout_icon.gif

public, protected, and private Work with PHP 5 Only The keywords public, protected, and private were introduced with PHP 5. Using them with methods or properties in PHP 4 will cause your script to fail.


    [ Team LiB ] Previous Section Next Section