Prev | Current Page 237 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"


?– Note The practice of creating objects based on predefined classes is often referred to as class
instantiation.
Objects are created using the new keyword, like this:
$employee = new Employee();
Once the object is created, all of the characteristics and behaviors defined within
the class are made available to the newly instantiated object. Exactly how this is
accomplished is revealed in the following sections.
Fields
Fields are attributes that are intended to describe some aspect of a class. They are
quite similar to standard 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 how to restrict access, using 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 Employee
{
public $name = "John";
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.


Pages:
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249