A field is used to describe the nature of a class.
A field is used to describe the nature of a certain aspect of a class. It is very similar to common PHP variables, but there are some minor differences. This section will introduce these differences. This section also describes how to declare and use fields. The next section describes how to use the field scope for access restrictions.
Declared Field
The rules for field Declaration are similar to those for variable Declaration. In fact, there is no difference. Because PHP is a loose language, fields do not even need to be declared. You can create and assign values to class objects at the same time, but this rarely happens. On the contrary, it is common to declare a field at the beginning of the class. In this case, you can assign an initial value to the field. Example:Copy codeThe Code is as follows: class Employee
{
Public $ name = "John ";
Private $ wage;
}
In this example, both the name field and the wage field have the scope Descriptor (public or Private). This is a common practice when declaring a field. After the declaration, each field can be used within the range indicated by the scope descriptor. If you do not understand the effect of the scope on class fields, do not worry. This issue will be introduced later.
Field Used
Unlike variables, fields must be referenced using the-> operator instead of the dollar sign. In addition, because the field value is generally unique to a given object, it has the following relationships with that object:Copy codeThe Code is as follows: $ object-> field
For example, at the beginning of this chapter, the description of the Employee class includes the field name, title, and wage. If you create an employee type object named $ Employee, you can reference these fields as follows:Copy codeThe Code is as follows: $ employee-> name
$ Employee-> title
$ Employee-> wage
When referencing a field in a class that defines a field, you must use the-> operator. Instead of using the corresponding class name, you must use the $ this keyword. $ This indicates that the field in the current class (the class where the field to be accessed or operated is located) is to be referenced. Therefore, if you want to create a method for setting the name field in the above-mentioned Employee class, it is as follows:Copy codeThe Code is as follows: function setName ($ name)
{
$ This-> name = $ name;
}