PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 3 ■ OBJECT BASICS


You can access property variables on an object-by-object basis using the characters '->' in
conjunction with an object variable and property name, like this:


$product1 = new ShopProduct();
print $product1->title;


default product


Because the properties are defined as public, you can assign values to them just as you can read
them, replacing any default value set in the class:


$product1 = new ShopProduct();
$product2 = new ShopProduct();
$product1->title="My Antonia";
$product2->title="Catch 22";


By declaring and setting the $title property in the ShopProduct class, I ensure that all ShopProduct
objects have this property when first created. This means that code that uses this class can work with
ShopProduct objects on that assumption. Because I can reset it, though, the value of $title may vary
from object to object.


■Note Code that uses a class, function, or method is often described as the class’s, function’s, or method’s


client or as client code. You will see this term frequently in the coming chapters.


In fact, PHP does not force us to declare all our properties in the class. You could add properties
dynamically to an object, like this:


$product1->arbitraryAddition = "treehouse";


However, this method of assigning properties to objects is not considered good practice in object-
oriented programming and is almost never used.
Why is it bad practice to set properties dynamically? When you create a class you define a type. You
inform the world that your class (and any object instantiated from it) consists of a particular set of fields
and functions. If your ShopProduct class defines a $title property, then any code that works with
ShopProduct objects can proceed on the assumption that a $title property will be available. There can
be no guarantees about properties that have been dynamically set, though.
My objects are still cumbersome at this stage. When I need to work with an object’s properties, I
must currently do so from outside the object. I reach in to set and get property information. Setting
multiple properties on multiple objects will soon become a chore:


$product1 = new ShopProduct();
$product1->title = "My Antonia";
$product1->producerMainName = "Cather";
$product1->producerFirstName = "Willa";
$product1->price = 5.99;


I work once again with the ShopProduct class, overriding all the default property values one by one
until I have set all product details. Now that I have set some data I can also access it:

Free download pdf