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!
|
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!
|