Skip to content

Instantly share code, notes, and snippets.

@iammerus
Created July 27, 2018 07:16
Show Gist options
  • Save iammerus/a0800b07e58089297c1735cfcc9fd382 to your computer and use it in GitHub Desktop.
Save iammerus/a0800b07e58089297c1735cfcc9fd382 to your computer and use it in GitHub Desktop.
Simple PSR4 Autoloader
<?php
spl_autoload_register(function($class) {
// Replace with your root name space
$root = "Foo\\";
// Remove the root namespace
if (substr($class, 0, strlen($root)) == $root) {
$relative = substr($class, strlen($root));
}
// Replace with your root directory
$base_dir = __DIR__ . "/classes/";
$filename = $base_dir . str_replace('\\', '/', $relative) . ".php";
// Check if the file exists
if (file_exists($filename)) {
require_once($filename);
if (class_exists($class)) {
return true;
}
}
return false;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment