Prev | Current Page 239 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

???
Public
You can declare fields in the public scope by prefacing the field with the keyword
public. An example follows:
170 CHAPTER 6 ?–  O BJECT-ORIENTED PHP
class Employee
{
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 Employee();
$employee->name = "Mary Swanson";
$name = $employee->name;
echo "New employee: $name";
Executing this code produces the following:
New employee: 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 are 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 encapsulated 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.


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