Skip to content

Instantly share code, notes, and snippets.

@adamgoucher
Created April 5, 2013 02:23
Show Gist options
  • Save adamgoucher/5316118 to your computer and use it in GitHub Desktop.
Save adamgoucher/5316118 to your computer and use it in GitHub Desktop.
My first attempt at a PHP autoloader. Is based on the one in PSR-0, but with the added check of constraining it to just the project's namespace which is the polite thing to do since spl_autoload functions are stackable
spl_autoload_register(function($className){
$projectNamespace = "PHPWebDriver";
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strrpos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
if (substr($namespace, 0, strlen($projectNamespace)) === $projectNamespace && file_exists($fileName)) {
require $fileName;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment