PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 3 ■ OBJECT BASICS

In order to make these objects more interesting, I can amend the ShopProduct class to support
special data fields called properties.


Setting Properties in a Class


Classes can define special variables called properties. A property, also known as a member variable,
holds data that can vary from object to object. So in the case of ShopProduct objects you may wish to
manipulate title and price fields, for example.
A property in a class looks similar to a standard variable except that you must precede your
declaration and assignment with a visibility keyword. This can be public, protected, or private, and it
determines the scope from which the property can be accessed.


■Note Scope refers to the function or class context in which a variable has meaning (it refers in the same way to


methods, which I will cover later in this chapter). So a variable defined in a function exists in local scope, and a


variable defined outside of the function exists in global scope. As a rule of thumb, it is not possible to access data


defined in a scope that is more local than the current. So if you define a variable inside a function, you cannot later


access it from outside that function. Objects are more permeable than this, in that some object variables can


sometimes be accessed from other contexts. Which variables can be accessed and from what context is


determined by the public, protected, and private keywords, as you shall see.


I will return to these keywords and the issue of visibility later in this chapter. For now, I will declare
some properties using the public keyword:


class ShopProduct {
public $title = "default product";
public $producerMainName = "main name";
public $producerFirstName = "first name";
public $price = 0;
}


As you can see, I set up four properties, assigning a default value to each of them. Any objects that I
instantiate from the ShopProduct class will now be prepopulated with default data. The public keyword
in each property declaration ensures that I can access the property from outside of the object context.


■Note The visibility keywords public, private, and protected were introduced in PHP 5. If you are running


PHP 4, these examples will not work for you. In PHP 4, all properties were declared with the var keyword, which is


identical in effect to using public. For the sake of backward compatibility, PHP 5 accepts var in place of public


for properties.

Free download pdf