Skip to content

Instantly share code, notes, and snippets.

@Andrewpk
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Andrewpk/11193501 to your computer and use it in GitHub Desktop.
Save Andrewpk/11193501 to your computer and use it in GitHub Desktop.
Simple php autoloader. Checks for constant 'CLASS_DIR' that specifies base directory for classes, otherwise will simply look in PSR-0 style directory structure in current directory.
<?php
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// From all I can find on it - PSR states class methods must have opening brace on new line - not plain ol' functions //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function autoload($className) {
$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 (defined('CLASS_DIR') && !empty(CLASS_DIR)) {
$fileName = CLASS_DIR . DIRECTORY_SEPARATOR . $fileName;
}
require $fileName;
}
spl_autoload_register("autoload");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment