Team LiB
Previous Section Next Section

Class Autoloading

When developing classes in PHP 4, there was no mechanism available to developers to automatically load a particular class on an as-needed basis. If you could potentially rely on a class in your scripts, you would have to include it when you began your application, regardless of whether you needed it. This is not the case in PHP 5, which allows you to specify a function to load classes as they are needed, if desired. This function is called the __autoload() function and has a prototype as follows:

function __autoload($classname);

$classname is the name of the class PHP could not find. Within the __autoload() function, you can place whatever logic you see fit to determine the location of a class and load it. This allows you the flexibility of loading classes from databases, remotely, from the file system, and so on quickly and easily. The only requirement when using this function is that before the function call terminates, the class must be loaded into PHP (generally through a require_once() statement). If the class has not been loaded when the __autoload() function terminates (or if the __autoload() function is not defined), PHP will terminate the script with an error indicating that the specified class could not be found.

As an example of the use of the __autoload() function, consider Listing 13.23:

Listing 13.23. Using the __autoload() Function
     function __autoload($class) {
          $files = array('MyClass' => "/path/to/myClass.class.php",
                         'anotherClass' => "/path/to/anotherClass.class.php");
          if(!isset($files[$class])) return;
     $a = new MyClass;
     $b = new anotherClass;

In Listing 13.23, the __autoload() function is used to load classes by looking up their location in a predefined associative array. Because neither MyClass nor anotherClass has been defined yet in this script, the __autoload() function will be called in both instances to give the script an opportunity to find the class itself.

    Team LiB
    Previous Section Next Section