6.14.2 __get()This is NOT the latest copy of this book; click here for the latest version.
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:
<?php
class dog {
public $Name;
public $DogTag;
// public $Age;
public function __get($var) {
print "Attempted to retrieve $var and failed...\n";
}
}
$poppy = new dog;
print $poppy->Age; ?>
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.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|