Prev | Current Page 240 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

Private scoping
is introduced next, and the section on properties soon follows.
?– Note As of PHP 6, you can use var in place of public. Before PHP 6, doing so raised a warning.
However, you should be sure to use var for compatibility reasons should you be creating software that
might be used on disparate server installations.
CHAPTER 6 ?–  O BJECT-ORIENTED PHP 171
Private
Private fields are only accessible from within the class in which they are defined. An
example follows:
class Employee
{
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 beginning of this chapter: encapsulation.
Consider the following example, in which a private field is manipulated by a public
method:
class Employee
{
private $name;
public function setName($name) {
$this->name = $name;
}
}
$staff = new Employee;
$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.


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