This is the first of three slightly unusual magic functions, and allows you to specify what to do if an unknown class variable is read from within your script. Take a look at the following script:

class dog {
// public $Age;

public function __get($var) {
"Attempted to retrieve $var and failed...\n";

$poppy = new dog;

Note that our dog class has $Age commented out, and we attempt to print out the Age value of $poppy. When this script is called, $poppy is found to not to have an $Age variable, so __get() is called for the dog class, which prints out the name of the property that was requested - it gets passed in as the first parameter to __get(). If you try uncommenting the public $Age; line, you will see __get() is no longer called, as it is only called when the script attempts to read a class variable that does not exist.

From a practical point of view, this means values can be calculated on the fly without the need to create and use accessor functions - not quite as elegant, perhaps, but a darn site easier to read and write.


Next chapter: __set() >>

Previous chapter: __autoload()

Jump to:


Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar