PHP allows including files in a very easy way. This is very useful when dealing with multiple classes. The spl_autoload_register(function) registers a function with the Standard PHP Library (SPL) __autoload queue. If the queue is not yet activated it will be activated. The function is a user defined function as seen in the example below. In order for the below example to work, make sure:
- All classes ar kept in a separate folder called classes.
- All class file names end with .class.php
- Copy/paste the below code to a php file (autoload.inc.php) in the includes folder.
- Include the autoload.inc.php in php scripts (or add it to the header file if you are using one).
<?php
spl_autoload_register('AutoLoad');
function AutoLoad($className) {
$path = "classes/";
$extension = ".class.php";
$fullPath = $path . $className . $extension;
include_once $fullPath;
}
?>
The above example does not include error handling.