[英]autoload and namespace
Suppose I have classes in same namespaces:假设我在相同的命名空间中有类:
directory :目录 :
(folder) a
(文件夹)一个
- a.php
一个.php
(folder) b
(文件夹) b
- b.php
b.php
- c.php
php
and we use namespace and __autoload
as you see: in folder b\\b.php
:我们使用命名空间和
__autoload
如您所见:在文件夹b\\b.php
:
<?php
namespace b;
use b as x;
function __autoload($clsName){
$clsName='../'.str_replace('\\', '/', $clsName).'.php';
require_once $clsName;
}
class b{
function __construct(){
print("b file<hr/>");
}
}
$t=new x\c(); // line 13
?>
and in folder b\\c.php
:并在文件夹
b\\c.php
:
<?php
namespace b;
class c{
function __construct(){
print("c file<hr/>");
}
}
?>
when we define $t=new x\\c
, __autoload
doesn't call!当我们定义
$t=new x\\c
, __autoload
不会调用! please help me :(请帮我 :(
error message:错误信息:
Fatal error: Class 'b\c' not found in C:\xampp\htdocs\project\TEST\b\b.php on line 13
You have not defined autoloader.您尚未定义自动加载器。 PHP looks for
__autoload
(or \\__autoload
- function defined in global namespace) while you have defined only \\b\\__autoload
(yes, functions are namespaced to!) PHP 查找
__autoload
(或\\__autoload
- 在全局命名空间中定义的函数),而您只定义了\\b\\__autoload
(是的,函数被命名为!)
How to fix it: move __autoload
declaration outside namespace如何修复:将
__autoload
声明移到命名空间之外
Better fix: you should use spl_autoload_register
更好的修复:您应该使用
spl_autoload_register
It's hard to see exactly what is going wrong.很难看出到底出了什么问题。 By the looks of the error, it appears that the
__autoload()
function isn't being called.从错误的外观来看,似乎没有调用
__autoload()
函数。 If it was I would expect the require_once
statement to fail with an error saying file not found, or something like that.如果是这样,我希望
require_once
语句失败,并出现错误,提示未找到文件,或类似的错误。
You could try by putting some debugging statements in your __autoload()
function to see what's going on, including a var_dump
of your $clsName
variable.您可以尝试在
__autoload()
函数中放入一些调试语句来查看发生了什么,包括$clsName
变量的var_dump
。
It might be worth noting the following message that appears in the PHP manual regarding autoloading :可能值得注意的是PHP 手册中出现的有关自动加载的以下消息:
spl_autoload_register() provides a more flexible alternative for autoloading classes.
spl_autoload_register()为自动加载类提供了更灵活的替代方法。 For this reason, using __autoload() is discouraged and may be deprecated or removed in the future.
出于这个原因,不鼓励使用__autoload()并且将来可能会被弃用或删除。
You should also note, that there is a "standard" for PHP autoloading, called PSR-0 .您还应该注意,PHP 自动加载有一个“标准”,称为PSR-0 。 Here is a link to an article that gives a good explanation of it.
这是一篇文章的链接,该文章对其进行了很好的解释。
In both the article and the PSR-0 document mentioned above, are example autoloaders that you can use.在上面提到的文章和PSR-0 文档中,都有您可以使用的示例自动加载器。 I would suggest using one of these than trying to implement your own.
我建议使用其中之一而不是尝试实现自己的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.