PHP __autoload() “not found” thowing exceptions

Posted on Mar 31, 2009 in PHP |


There is much debate about the __autoload function introduced in PHP5. I personally love it as all those requires, includes etc. made programs quite messy, and frankly annoy me if you create loads of pages that keep on requiring the same classes.

The one fault __autoload has though is that Exceptions cannot be thrown, and that to me would give potential for some great degradeablity.

Thankfully, there are a few ways of hacking the autoload function so that it does throw an Exception. The most common way is to create a class with the class name the autoload function is looking for using the eval() function, and then throw an exception once autoload is happy.

This is my personal favorite (note that usually I make the eval() bits one line but for your readability here i’ve indented it).

function __autoload($class_name){
	//Do your searching and including here
	if( (@include($path.DS."$classFilename")) ){
		return;
	}
	//If it reached here, then you've not found anything, so create a class dynamically and throw an error
	$class_name = preg_replace("/(|)/", "*", stripslashes($class_name) );
	$class_name = str_replace('.', '', $class_name);
	$namespace = substr($class_name, 0, strrpos($class_name, '::'));
	$localClassName = substr($class_name, strrpos($class_name, '::') + 2);
	if($namespace) {
		eval("
		namespace $namespace;
		class $localClassName {
			function __construct() {
				throw new Exception('Class $namespace::$localClassName not found', 1001);
		} static function __callstatic($m, $args) {
			throw new Exception('Class $class_name not found', 1001);
		}
		function x_notaclass_x(){}
		}
		");
	} else {
		eval("
		class $class_name {
			function __construct() {
				throw new Exception('Class $class_name not found', 1001);
			}
			static function __callstatic($m, $args) {
				throw new Exception('Class $class_name not found', 1001);
			}
			function x_notaclass_x(){}
		}
		");
	}
	return;
}