【发布时间】:2018-08-25 09:48:02
【问题描述】:
我正在从https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md 测试 PSR-4 自动加载器,但有些东西不工作。
错误:
致命错误:未捕获的错误:在 C:\xampp\htdocs\Home\foo-bar\index.php:11 中找不到类 'Foo\Bar\Qux\Quux' 堆栈跟踪:#0 {main} 抛出C:\xampp\htdocs\Home\foo-bar\index.php 在第 11 行
行:
新的\Foo\Bar\Qux\Quux;
我的文件:
- index.php
- 示例
- loader.php
- 源
- 曲克斯
- Quux.php
- Baz.php
- 曲克斯
- 测试
- 曲克斯
- Quux.php
- BazTest.php
- 曲克斯
index.php:
<?php
require_once "Example/loader.php";
$loader = new \Example\Psr4AutoloaderClass;
$loader->register();
$loader->addNamespace('Foo\Bar', '/src');
$loader->addNamespace('Foo\Bar', '/tests');
new \Foo\Bar\Qux\Quux;
loader.php:
<?php namespace Example;
class Psr4AutoloaderClass
{
protected $prefixes = array();
public function register()
{
spl_autoload_register(array($this, 'loadClass'));
}
public function addNamespace($prefix, $base_dir, $prepend = false)
{
// normalize namespace prefix
$prefix = trim($prefix, '\\') . '\\';
// normalize the base directory with a trailing separator
$base_dir = rtrim($base_dir, DIRECTORY_SEPARATOR) . '/';
// initialize the namespace prefix array
if (isset($this->prefixes[$prefix]) === false) {
$this->prefixes[$prefix] = array();
}
// retain the base directory for the namespace prefix
if ($prepend) {
array_unshift($this->prefixes[$prefix], $base_dir);
} else {
array_push($this->prefixes[$prefix], $base_dir);
}
}
public function loadClass($class)
{
// the current namespace prefix
$prefix = $class;
while (false !== $pos = strrpos($prefix, '\\')) {
// retain the trailing namespace separator in the prefix
$prefix = substr($class, 0, $pos + 1);
// the rest is the relative class name
$relative_class = substr($class, $pos + 1);
// try to load a mapped file for the prefix and relative class
$mapped_file = $this->loadMappedFile($prefix, $relative_class);
if ($mapped_file) {
return $mapped_file;
}
$prefix = rtrim($prefix, '\\');
}
return false;
}
protected function loadMappedFile($prefix, $relative_class)
{
// are there any base directories for this namespace prefix?
if (isset($this->prefixes[$prefix]) === false) {
return false;
}
foreach ($this->prefixes[$prefix] as $base_dir) {
$file = $base_dir
. str_replace('\\', '/', $relative_class)
. '.php';
// if the mapped file exists, require it
if ($this->requireFile($file)) {
// yes, we're done
return $file;
}
}
// never found it
return false;
}
protected function requireFile($file)
{
if (file_exists($file)) {
require $file;
return true;
}
return false;
}
}
Quux.php:
<?php namespace Foo\Bar\Qux;
class Quux {
public function __construct() {
echo "Hello";
}
}
感谢您的帮助。
【问题讨论】:
-
自己找到的。 $file 路径错误。
标签: php autoload autoloader