Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Cabbit

macrumors 68020
Original poster
Jan 30, 2006
2,128
1
Scotland
PHP:
function autoLoader($className)
{
	//Directories added here must be relative to the script going to use this file. 
	$directories = array
	(
		'../application/classes/*/'
	);

	//File naming formats
	$fileNameFormats = array
	(
		'%s.class.php'
	);

	// this is to take care of the PEAR style of naming classes
	$path = str_ireplace('_', '/', $className);

	if(@include_once $path.'.php')
	{
		return;
	}

	foreach($directories as $directory)
	{
		foreach($fileNameFormats as $fileNameFormat)
		{
			$path = $directory.sprintf($fileNameFormat, $className);
			if(file_exists($path))
			{
				include_once $path;
				return;
			}
		}
	}
}
spl_autoload_register('autoLoader');

I seem to be missing the logic some where as i just can't get this to work, my error log is reporting it can't find the class in the directory i am pointing too.
 
Yep in the previous version of the script * opens up all the directories though this is rather a primitive way of doing it as it will just brute open every directory in the folder.

The directory is set up as

root
application​
classes​
TestClass​
TestClass.php​
html​
bootstrap.php (where the script is called)​


Old Function
PHP:
foreach(glob('../application/classes/*/*.php') as $ClassFilename) {
     require_once($ClassFilename);
}
 
I have made a simplified version that works quite well.

PHP:
function __autoload($class_name) {
    require_once '../application/classes/'.$class_name.'/' . $class_name . '.class.php';
}
 
PHP:
foreach(glob('../application/classes/*/*.php') as $ClassFilename) {
     require_once($ClassFilename);
}

glob() is the reason * works in that example; in the first, it is going to be checking for the class 'foo' in:
../application/classes/*/foo.class.php

I have made a simplified version that works quite well.
PHP:
function __autoload($class_name) {
    require_once '../application/classes/'.$class_name.'/' . $class_name . '.class.php';
}

That's essentially what my standard __autoload() looks like. I don't stick each class in its own directory though. I have a few subdirectories and prefix the names of the classes found therein, and the __autoload() checks for the prefix in the class name to figure out where to look for the class.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.