Oct 16th

PHP Class Autoloader Function

Anyone who has done serious work with PHP since 5.0 knows the way to stay future proof is to adopt and love like it was your own the object oriented programming model. This little snippet has gone a LONG way to making my life easier. To use it, simply include it in your globally included functions library (yes, functions not objects.. regular every day function methods).

In the snippet below there is a constant “PATH_CLASSES”, in my global definitions I have this defined as the absolute path to my class libraries which are all in the same directory for this purpose.

function __autoload( $class_name )
{
	$file_formats = array('%s.php', '%s.class.php', 'class.%s.php', '%s.inc.php');
	foreach ( $file_formats as $file_format )
	{
		$file = PATH_CLASSES.sprintf($file_format, strtolower($class_name));
		if ( file_exists($file) ) require_once($file);
	}
	return;
}

Leave a Reply