Hudzilla.org - the homepage of Paul Hudson
Contents > Objects > Magic functions Wish List | Report Bug | About Me ]

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.





<< 6.14.1 __autoload()   6.14.3 __set() >>
Table of Contents
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!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
Guna - 30 Aug 2008

if __get($var) function returns any value , that is substituted to the non-existing class varible

try out the following:

class foo{
function __get($var){
echo "<br>variable $var not available<br>";
return "Guna<br>";
}
}

$foo = new foo;

echo $foo->name;



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is six plus ten?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow