One thing that can be annoying about PHP is that you have to include the class-files before you can create a class, and if you have alot of classes the list of includes can get quite long. You could create a dedicated include file and throw all the include statements into that file, but do you really want to load all those file everytime, isn’t it better to load only the files you need?

Load on demand

You could include the file right before you construct the class, but this gives you more code to handle, not that it’s that much of a deal with one extra line of code per class, but you should check if the class file is allready loaded somewhere else in the code, and what if the class extends another class and so on. Now the one line doesn’t sound like one line anymore.

Lucky for you (and me) PHP 5 gives you the ability to define a autoload function which is automatically called in case you are trying to use a class/interface 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.

function __autoload($class) {

    // Check if file exists
    if(file_exists('path_to_your_class_directory/'.$class.'.class.php')) {

        //Include the file
        include('path_to_your_class_directory/'.$class.'.class.php');

   } else {

        //Error: File does not exist
        die('Failed to load class: '.$class);

    }
}

$vehicle = new car();

Here we first define the autoload function, before we try to initialize a class without loading it. PHP checks if the class car is defined, and if it’s not it will execute the __autoload function if it is defined, in our custom autoload function we have our own error checking, checking if the file exists before loading it. If successful PHP can now create the object.