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.infofor the property name by declaring two functions, getName() and setName(), respectively, andembedding the appropriate syntax within each. An example of this strategy is presented at theconclusion of this section.<strong>PHP</strong> version 5 and newer does offer some semblance of support for property overloading, done byoverloading the __set and __get methods. These methods are invoked if you attempt to reference amember variable that does not exist within the class definition. Properties can be used for a variety ofpurposes, such as to invoke an error message, or even to extend the class by actually creating newvariables on the fly. Both __get and __set are introduced in this section.Setting Properties with the __set() MethodThe mutator, or setter method, is responsible for both hiding property assignment implementation andvalidating class data before assigning it to a class property. Its prototype follows:boolean __set([string property_name],[mixed value_to_assign])It takes as input a property name and a corresponding value, returning TRUE if the method issuccessfully executed and FALSE otherwise. An example follows:class Employee{var $name;function __set($propName, $propValue){echo "Nonexistent variable: \$$propName!";}}$employee = new Employee ();$employee->name = "Mario";$employee->title = "Executive Chef";This results in the following output:Nonexistent variable: $title!You could use this method to actually extend the class with new properties, like this:class Employee{public $name;function __set($propName, $propValue){$this->$propName = $propValue;}}$employee = new Employee();142

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

Saved successfully!

Ooh no, something went wrong!