Fields are attributes that are intended to describe some aspect of a class. They are quite similar to normal PHP variables, except for a few minor differences, which you’ll learn about in this section. You’ll also learn how to declare and invoke fields, and read all about field scopes.
Declaring Fields
The rules regarding field declaration are quite similar to those in place for variable declaration:
essentially, there are none. Because PHP is a loosely typed language, fields don’t even necessarily need to be declared; they can simply be created and assigned simultaneously by a class object, although you’ll rarely want to do that. Instead, common practice is to declare fields at the beginning of the class. Optionally, you can assign them initial values at this time. An example follows:
class Staff {
public $name = "Lackey";
private $wage;
}
In this example, the two fields, name and wage, are prefaced with a scope descriptor (public or private), a common practice when declaring fields. Once declared, each field can be used under the terms accorded to it by the scope descriptor. If you don’t know what role scope plays in class fields, don’t worry; that topic is covered later in this chapter.
Invoking Fields
Fields are referred to using the -> operator and, unlike variables, are not prefaced with a dollar sign. Furthermore, because a field’s value typically is specific to a given object, it is correlated to said object like this:
$object->field
For example, the Staff class described at the beginning of this chapter included the fields name, title, and wage. If you created an object named $employee of type Staff, you would refer to these fields like this:
$employee->name
$employee->title
$employee->wage
When you refer to a field from within the class in which it is defined, it is still prefaced with the -> operator, although instead of correlating it to the class name, you use the $this keyword.
$this implies that you’re referring to the field residing in the same class in which the field is being accessed or manipulated. Therefore, if you were to create a method for setting the name field in the aforementioned Staff class, it might look like this:
function setName($name) {
$this->name = $name;
}
Field Scopes
PHP supports five class field scopes: public, private, protected, final, and static. The first four are introduced in this section, and the static scope is introduced in the later section, “Static Class Members.”
Public
You can declare fields in the public scope by prefacing the field with the keyword public.
An example follows:
class Staff {
public $name;
/* Other field and method declarations follow... */
}
Public fields can then be manipulated and accessed directly by a corresponding object, like so:
$employee = new Staff();
$employee->name = "Mary Swanson";
$name = $employee->name;
echo "New staff member: $name";
Not surprisingly, executing this code produces:
New staff member: Mary Swanson
Although this might seem like a logical means for maintaining class fields, public fields are actually generally considered taboo to OOP, and for good reason. The reason for shunning such an implementation is that such direct access robs the class of a convenient means for enforcing any sort of data validation. For example, nothing would prevent the user from assigning name like so:
$employee->name = "12345";
This is certainly not the kind of input you were expecting. To prevent such mishaps from occurring, two solutions are available. One solution involves encapsulating the data within the object, making it available only via a series of interfaces, known as public methods. Data encap- sulated in this way is said to be private in scope. The second recommended solution involves the use of properties, and is actually quite similar to the first solution, although it is a tad more convenient in most cases. Private scoping is introduced next, whereas properties are discussed in the later section, “Properties.”
Private
Private fields are only accessible from within the class in which they are defined. An example follows:
class Staff {
private $name;
private $telephone;
}
Fields designated as private are not directly accessible by an instantiated object, nor are they available to subclasses. If you want to make these fields available to subclasses, consider using the protected scope instead, introduced next. Instead, private fields must be accessed via publicly exposed interfaces, which satisfies one of OOP’s main tenets introduced at the begin- ning of this chapter: encapsulation. Consider the following example, in which a private field is manipulated by a public method:
<?php
class Staff {
private $name;
public function setName($name) { $this->name = $name;
} }
$staff = new Staff;
$staff->setName("Mary");
?>
Encapsulating the management of such fields within a method enables the developer to maintain tight control over how that field is set. For example, you could add to the setName() method’s capabilities, to validate that the name is set to solely alphabetical characters and to ensure that it isn’t blank. This strategy is much more reliable than leaving it to the end user to provide valid information.
Protected
Just like functions often require variables intended for use only within the function, classes can include fields used for solely internal purposes. Such fields are deemed protected, and are prefaced accordingly. An example follows:
class Staff {
protected $wage;
}
Protected fields are also made available to inherited classes for access and manipulation, a trait not shared by private fields. Any attempt by an object to access a protected field will result in a fatal error. Therefore, if you plan on extending the class, you should use protected fields in lieu of private fields.
Final
Marking a field as final prevents it from being overridden by a subclass, a matter discussed in further detail in the next chapter. A finalized field is declared like so:
class Staff {
final $ssn;
...
}
You can also declare methods as final; the procedure for doing so is described in the later section, “Methods.”