PHP - Automatically Loading Class Files

Introduction

It's a good idea to keep your classes in separate script files, one class per file.

For example, you might create a class called Person and store it in a file called Person.php inside a classes folder (so that you know that Person.php contains a class).

Then, when your script needs to create a Person object, it can include the Person.php file to create the class, then go ahead and create an object from the class:

<?php
          require_once("classes/Person.php");
          $p = new Person();
?>

require_once() lets you include one PHP script file inside another, which means you can break up your PHP application into small, manageable script files.

Class autoloading.

With autoloading, you create an __autoload() function somewhere in your script.

This function should accept a class name as an argument.

Then, whenever another part of your script attempts to create a new object from a nonexistent class, __autoload() is automatically called, passing in the class name.

This gives your __autoload() function a chance to find and include the class file, thereby allowing the PHP engine to carry on and create the object.

Here's an example __autoload() function:

function __autoload($className) {
            $className = str_replace ("..","", $className);
            require_once("classes/$className.php");
}

Here, this function stores the name of the nonexistent class in a $className parameter.

It then filters this parameter to ensure it contains no ".." substrings.

Finally, it calls PHP's require_once() function to load the file in the classes folder with the same name as the missing class.

This should cause the class to be created, allowing the object in turn to be created from the class.

For example, imagine the same script contained the following code:

$p = new Person;

When the PHP engine encounters the new Person construct, it looks to see if the Person class has been defined.

If not, it calls the previously defined __autoload() function.

This in turn includes and runs the file Person.php inside the classes folder, which creates the class and allows the new Person object to be created.

If the PHP engine can't find an __autoload() function, or if your __autoload() function fails to load the Person class, the script exits with a "Class 'Person' not found" error.

Related Topic