Last active
July 12, 2024 23:51
-
-
Save cloudinstone/57714cba4bcde7b88331d00e7323952d to your computer and use it in GitHub Desktop.
PHP Autoloader Class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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