__get()

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 learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: __set() >>

Previous chapter: __autoload()

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.