Autoloading Classes with PHP

November 19th 2012

Thankfully, long gone are the days of manually specifying require() or include() for every single file you need while developing a project.

If you follow the standards, you should structure your files like this:

A class called:

Text Snippet:
Super_Duper_Class

Should be in the location of:

Text Snippet:
Super/Duper/Class.php

Now, this may seem a bit strange, I know back in the day when I started structuring like this it took some getting used to, but it allows me to do something extra special.

If you require an Autoloader file in your script, then loading class files when and if needed is so much easier.

Here's the very basic code to make this happen:

PHP Code:
<?php
$var 
= function($name){
        
$path implode(DIRECTORY_SEPARATOR,explode("_",$name)) . ".php";
        
// Depending on your setup, you may need to declare the absolute
        // root of your project in the include() below
        
include_once($path);
};
spl_autoload_register($var$throw truetrue);

That basically tells PHP to turn the _ in a class name and convert it into a DIRECTORY_SEPARATOR and load the PHP file, which should be named accordingly.

A word of warning:

Linux and Windows are not the same. Microsoft apparently decided the case sensitivity on file and folder names didn't matter, so a file called test.php is basically the same as Test.php

Linux thankfully did things the right way. test.php and Test.php are 2 completely different files. Remember to always develop for your target platform. And please, don't use Windows Servers in a production environment. It's just amateur.