11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 6 • OBJECT-ORIENTED <strong>PHP</strong>www.it-ebooks.infoso:Public properties can then be accessed and manipulated directly via the corresponding object, like$employee = new Employee();$employee->name = "Mary Swanson";$name = $employee->name;echo "New employee: $name";Executing this code produces the following:New employee: Mary SwansonAlthough this might seem like a logical means for maintaining class properties, public properties areactually generally considered taboo to OOP, and for good reason. The reason for shunning such animplementation is that such direct access robs the class of a convenient means for enforcing any sort ofdata 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 occurrences, two solutionsare available. One solution involves encapsulating the data within the object, making it available only viaa series of interfaces, known as public methods. Data encapsulated in this way is said to be private inscope. The second recommended solution involves the use of properties and is actually quite similar tothe first solution, although it is a tad more convenient in most cases. Private scoping is introduced next,and the section on properties soon follows.PrivatePrivate properties are only accessible from within the class in which they are defined. An examplefollows:class Employee{private $name;private $telephone;}Properties designated as private are not directly accessible by an instantiated object, nor are theyavailable to child classes (the concept of a child class is introduced in the next chapter). If you want tomake these properties available to child classes, consider using the protected scope instead, introducednext. Note that private properties must be accessed via publicly exposed interfaces, which satisfies oneof OOP’s main te<strong>net</strong>s introduced at the beginning of this chapter: encapsulation. Consider the followingexample, in which a private property is manipulated by a public method:class Employee{private $name;public function setName($name) {$this->name = $name;}140

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!