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 ...

Get Sams Teach Yourself PHP in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.