__autoload()

This global function is called whenever you try to create an object of a class that hasn't been defined. It takes just one parameter, which is the name of the class you have not defined. If you define an object as being from a class that PHP does not recognise, PHP will run this function, then try to re-create the object - you have a second chance to have the right class.

As a result, you can write scripts like this:

<?php
    
function __autoload($Class) {
        print
"Bad class name: $Class!\n";
        include
"barclass.php";
    }

    
$foo = new Bar;
    
$foo->wombat();
?>

Here we try and create a new object of type Bar, but as you can see it does not exist. __autoload() is therefore called, with "Bar" being passed in as its first parameter. __autoload() then include() s the file barclass.php, which contains the class definition of Bar. PHP will again try and create a new Bar, and this time it will succeed, which means we can work with $foo as normal.

For more advanced scripts, you can try include() ing the parameter passed into __autoload() - that way you just need to define each class in a file of its own, with the file named after the class. This has been optimised so that calls to __autoload() are cached - don't be afraid to make good use of this technique. One of the lead developers of PHP, Andi Gutmans, said, "after having written many examples and worked with it for some time, I'd only ever code this way" - as firm an endorsement as anyone could ask for!

 

Next chapter: __get() >>

Previous chapter: Magic functions

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar