PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 3 ■ OBJECT BASICS

print "author: {$product1->producerFirstName} "
."{$product1->producerMainName}\n";


This outputs

author: Willa Cather


There are a number of problems with this approach to setting property values. Because PHP lets you
set properties dynamically, you will not get warned if you misspell or forget a property name. For
example, I might mistakenly type the line


$product1->producerMainName = "Cather";


as


$product1->producerSecondName = "Cather";


As far as the PHP engine is concerned, this code is perfectly legal, and I would not be warned. When
I come to print the author’s name, though, I will get unexpected results.
Another problem is that my class is altogether too relaxed. I am not forced to set a title, or a price, or
producer names. Client code can be sure that these properties exist but is likely to be confronted with
default values as often as not. Ideally, I would like to encourage anyone who instantiates a ShopProduct
object to set meaningful property values.
Finally, I have to jump through hoops to do something that I will probably want to do quite often.
Printing the full author name is a tiresome process:


print "author: {$product1->producerFirstName} "
."{$product1->producerMainName}\n";


It would be nice to have the object handle such drudgery on my behalf.
All of these problems can be addressed by giving the ShopProduct object its own set of functions that
can be used to manipulate property data from within the object context.


Working with Methods


Just as properties allow your objects to store data, methods allow your objects to perform tasks. Methods
are special functions declared within a class. As you might expect, a method declaration resembles a
function declaration. The function keyword precedes a method name, followed by an optional list of
argument variables in parentheses. The method body is enclosed by braces:


public function myMethod( $argument, $another ) {
// ...
}


Unlike functions, methods must be declared in the body of a class. They can also accept a number
of qualifiers, including a visibility keyword. Like properties, methods can be declared public, protected,
or private. By declaring a method public, you ensure that it can be invoked from outside of the current
object. If you omit the visibility keyword in your method declaration, the method will be declared public
implicitly. I will return to method modifiers later in the chapter.

Free download pdf