【发布时间】:2021-06-29 09:22:20
【问题描述】:
我尝试编写以下代码,但无法弄清楚为什么它在 spl_autoload_register() 中找不到具有命名空间的类?
我得到的错误是:
警告:require_once(src/test\StringHelper.php):打开失败 流:没有这样的文件或目录
Autoloader.php 文件:
<?php
spl_autoload_register(function($classname){
require_once "src/$classname.php"; // NOT WORKING DYNAMICALLY
// require_once "src/StringHelper.php"; // WORKING WHEN HARD CODED
});
$stringHelper1 = new test\StringHelper(); // Class with namespace defined
echo $stringHelper1->hello() . PHP_EOL; // returns text
src 文件夹内的StringHelper.php:
<?php namespace test;
class StringHelper{
function hello(){
echo "hello from string helper";
}
}
如果这有所作为,我也会使用 XAMPP。
【问题讨论】:
-
因为
$classname是包含命名空间的fully qualified name。如果你只需要,你需要去掉类名 -
@mario 抱歉,我之前在使用“/”进行测试时尝试过此操作,但仍然没有成功,因此被删除并忘记更新错误消息。
-
@apokryfos 请您发布一个代码示例供我查看?谢谢
-
@Jeto - 这个答案是关于从类实例中获取名称,而不是字符串(这会给他们)。接受的答案甚至使用反射来获取名称。
标签: php oop xampp namespaces php-7