PHP Class Autoloading

By Deane Barker on July 5, 2005

PHP: Autoloading Objects: Something I always liked about COM was that you could register a DLL on the server and call it from code without having to reference a specific location — it was just “out there” somewhere, and the server knew where to find it.

With PHP4 and older, you have to include the class definition, which is kind of a drag because on a big app you end up with dozens and dozens of file includes to get all the class definitions in. If you have some big classes, this can suck up memory like crazy.

PHP5 — which I haven’t made the jump to yet — fixes this with an “autoload” function. You can instantiate an object wherever you like, and if it hasn’t been defined yet, you can tell PHP how to find it.

In PHP 5 [including class definitions] is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class which hasn’t been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.

No more class file includes. Yippee.

This is even better than COM because it means you can have a class on a server twice. If you tweak a class for a particular app, you don’t have to register a different DLL, you just hack your autoload function so that it looks in the right spot for that particular app.

I imagine this isn’t an exclusive concept to PHP, but it’s a nice step up from PHP4.