__get and __set
To set the context for this discussion, remember that we spent some time discussing accessor, or set and get methods, in Chapter 6. There I argued that instance variables should be made private and only retrieved or changed through accessor methods. Doing otherwise violates the object-oriented (OO) principle of data hiding (or encapsulation if you prefer) and leaves instance variables exposed to inadvertent changes.
PHP 5 introduces magic set and get methods for undefined instance variables. Let's see what this means by looking at an example. Suppose you have a class, Person, devoid of any data members or methods, defined as follows:
class Person{ }
PHP allows you to do the following:
$p = new Person(); $p->name = "Fred"; ...
Get Object-Oriented PHP now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.