Skip to content

Instantly share code, notes, and snippets.

@cloudinstone
Last active July 12, 2024 23:51
Show Gist options
  • Save cloudinstone/57714cba4bcde7b88331d00e7323952d to your computer and use it in GitHub Desktop.
Save cloudinstone/57714cba4bcde7b88331d00e7323952d to your computer and use it in GitHub Desktop.
PHP Autoloader Class.
<?php
namespace DressPress;
final class Autoloader
{
private $namespace;
private $filepath;
public function __construct(string $namespace, string|null $filepath = null, bool $throw = true, bool $prepend = false)
{
$this->namespace = $namespace;
$this->filepath = $filepath ?? dirname(__FILE__);
spl_autoload_register(array($this, 'callback'), $throw, $prepend);
}
public function callback($class)
{
$namespace = $this->namespace;
if (strpos($class, $namespace) !== 0) {
return;
}
$class = str_replace('\\', DIRECTORY_SEPARATOR, $class);
$class = substr($class, strlen($namespace . DIRECTORY_SEPARATOR));
$file = $this->filepath . DIRECTORY_SEPARATOR . $class . '.php';
if (file_exists($file)) {
require $file;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment