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

6.14.1     __autoload()

This is NOT the latest copy of this book; click here for the latest version.

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 __autload() are cached - don't be afraid to make good use of this technique. At O'Reilly's Open Source Conference in 2004, 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!





<< 6.14 Magic functions   6.14.2 __get() >>
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
Be the first to add a comment to this chapter!



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 eight plus one?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow