Tim Igoe's Web Design, Development and Hosting Blog

PHP – Autoload Includes based on Class name

[b]Please note, this code is for PHP5 and above only.[/b]

While writing lots of object orientated PHP5 code, you may find you need lots of include() or require() statements, it gets repetitive to keep writing these things in every file you use.

PHP has an answer to this, in the form of an __autoload() function that is available for you to set.


define(BASE_PATH, dirname(__FILE__));
// Autoload function
// This is used by PHP when it can't find a class
function __autoload($className)
{
// Replace _'s in the class name with /'s (enables us
// to arrange the includes nicely in folders)
$file = str_replace('_', '/', strtolower($class)) . '.php';

// Lets check the file exists, then the class exists in the file
// otherwise we’ll error gracefully
if (@filesize(BASE_PATH . ‘/includes/’ . $file) > 0)
require_once(BASE_PATH . ‘/includes/’ . $file);
else
die(‘Class File Not Found’);
}

Putting this code in an include, and then include it, will allow you to automatically load all other includes from an ‘includes’ folder. File naming needs to be a little more intelligent however, for example making the filename be the same as that of the class contained within it. While very useful, it can’t include ALL needed includes, it only works for classes currently.

Base classes all reside within the includes folder, if you wish to extend a class, use the classname and make a folder, and then within this put the files named in the same format.

For example, if you were to make a validator system, the file layout may look something like…

/site/
index.php
config.php
autoload.php
includes/
database.php
validator.php
validator/
text.php
integer.php

Exit mobile version