这个问题在这里已经有了答案:
How do I use PHP namespaces with autoload?
(13 个回答)
4年前关闭。
我试图了解如何为具有命名空间的简单应用程序定义工作自动加载器。
我创建了以下结构:
public
index.php
src
Models
WordGenerator.php
显然,以后它会增长。
WordGenerator.php
文件如下:<?php
namespace Models;
class WordGenerator {
public $filename;
public function __construct($filename) {
$this->_filename = $filename;
}
}
现在我尝试在
index.php
中创建此对象的实例:<?php
use \Models;
$wg = new WordGenerator("words.english");
显然我得到了 fatal error ,因为我没有定义
autoloader
.但是,根据文档,我只能通过 $classname
.我应该如何定义自动加载器函数以获取由 use
声明的命名空间然后声明??[编辑]
刚才理解错了。所以这是我的代码
index.php
:spl_autoload_register(function ($className) {
$className = ltrim($className, '\\');
$prepend = "..\\src\\";
$fileName = "{$prepend}";
$namespace = '';
if ($lastNsPos = strrpos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = $prepend.str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
require $fileName;
});
//require '../src/Models/WordGenerator.php';
use Models;
$wg = new WordGenerator("words.english");
echo $wg->getRandomWord();
现在,这不起作用,我得到:
Warning: The use statement with non-compound name 'Models' has no effect in C:\xampp\htdocs\Hangman\public\index.php on line 22
Warning: require(..\src\WordGenerator.php): failed to open stream: No such file or directory in C:\xampp\htdocs\Hangman\public\index.php on line 16
Fatal error: require(): Failed opening required '..\src\WordGenerator.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\Hangman\public\index.php on line 16
但是当我改变时
new WordGenerator
至 new \Models\WordGenerator
有用。现在,问题是:如何将 use 语句声明的命名空间传递给自动加载器函数以使其正常工作?
最佳答案
您的 use
说法不正确。你要use Models\WordGenerator;
use
运算符除了别名之外不声明任何内容。考虑扩展形式:
use Models\WordGenerator as WordGenerator;
这是等效的。
您可以为命名空间而不是类指定别名,但它不会以您尝试的方式工作。例如:
use Models as Foo;
$wg = new Foo\WordGenerator("words.english");
会工作。然而:
use Models;
相当于:
use Models as Models;
这实际上什么都不做。
如需更多信息,请参阅 Using namespaces: Aliasing/Importing在 PHP 手册中。
关于带有命名空间的 PHP 自动加载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25958243/