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 andwage, are prefaced with a scope descriptor (publicorprivate), 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, theStaffclass described at the beginning of this chapter included the fieldsname,title, andwage. If you created an object named$employeeof typeStaff, 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$thiskeyword.$thisimplies 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 aforementionedStaffclass, it might look like this:
function setName($name) { $this->name = $name; }
Please check back next week for the continuation of this article.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.