The Sapience Society The advice of a self-proclaimed technological ninjician

5Aug/102

Automagically Load Class Files in PHP

If you have very much experience with writing medium/large PHP based projects, you've probably run into the following annoyance:

You have a bunch of classes that you use ubiquitously, some which you wrote and some which others have written. Each file has a single class in it, but since the classes are from difference sources, some of their files have non-consistent naming conventions. You have to include classes into the files which use them, so you might include all of the classes in a header file, but that will cause unnecessary overhead because even unneeded classes get included in ever file which uses the header at all. The other option is to individually include only the necessary classes into the files that use them, but what a pain in the ass!

Fortunately there is a third option, available in PHP 5.0+; it's called Autoloading Classes. Basically, as soon as an object of a class is created for which the source file has not yet been included a function called __autoload is called. Using that function, we can then include the appropriate class file just before the object is created. Thus avoiding including any additional classes via a header or having to type out extra includes. So how does this magical function work?