UltraMega Blog
29May/091

Snippet: Autoloading Objects (PHP 5)

When writing the PHP that powers TempServers, I wrote the core functions into classes for better organization and efficiency. To make things further organized, each class is stored in individual source files, no matter how small. The problem here is keeping track of which classes are used where, in order to include the appropriate source files. Fortunately, PHP 5 offers a solution: autoloading.

This comes in the form of the __autoload function which automatically gets called if a class is called that does not exist. Here's what it looks like:

function __autoload($class) {
    require_once(strtolower($class) . '.class.php');
}

Usage

  1. Place each PHP class in individual files named after the class followed by .class.php (Example: class MyClass goes in a file named myclass.class.php).
  2. Include the code snipped above into any file that might use one of your classes.

For more details, check out the PHP manual: http://www.php.net/manual/language.oop5.autoload.php

28May/092

Follow us on Twitter

You can now follow UltraMega Software on Twitter: @ultramegasoft

We'll keep you up to date on any projects we're working on as well as any useful information that we find. New blog posts will also be posted there.

Tagged as: 2 Comments