自动加载和名称空间 [英] autoload and namespaces

查看:71
本文介绍了自动加载和名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用PHP很长时间了,但是现在开始尝试使用诸如命名空间之类的新语言功能.我有一个有关自动加载的问题,我在网络搜索中找不到足够的答案.

I've been working with PHP for a long time, but am now starting to experiment with newer language features such as namespaces. I have a question regarding autoloading that I haven't been able to find an adequate answer to in my web searching.

假设我在不同的命名空间中有类:

Suppose I have classes in different namespaces:

namespace foo\bar\baz;

class Quux
{
}

namespace fred\barney\wilma;

class Betty
{
}

然后假设我有一个自动加载器,它假定名称空间和目录结构之间存在1:1映射:

Then suppose I had an autoloader that assumes that there's a 1:1 mapping between namespaces and directory structures:

function autoload ($className)
{
    $className = str_replace ('\\', DIRECTORY_SEPERATOR, $className);
    include ($className . 'php');
}

spl_autoload_register ('autoload');

是在所有情况下将完全限定的名称空间传递给自动加载器,还是自动加载器需要考虑当前正在使用的名称空间?

Does the fully qualified namespace get passed to the autoloader under all circumstances, or does the autoloader need to take the namespace currently being used into account?

例如,如果我执行以下操作:

For example, if I do the following:

$a = new \foo\bar\baz\Quux;
$b = new \fred\barney\wilma\Betty;

自动装带器应能正常工作.

the autoloader should work fine.

但是,如果我执行以下操作怎么办?

But what if I do the following?

use \foo\bar\baz as FBB;
$a = new Quux;
$b = new \fred\barney\wilma\Betty;

当尝试实例化新的Quux时,自动加载器是否仍将\foo\bar\baz\Quux作为类名参数?还是应该得到FBB\Quux,甚至仅仅是Quux?

When attempting to instantiate a new Quux, will the autoloader still get \foo\bar\baz\Quux as the class name argument? Or should it get FBB\Quux, or even just Quux?

如果是后者,我可以使用__NAMESPACE__或其他类似的机制从自动加载器中确定该类应位于的名称空间吗?

If the latter, can I determine the namespace the class is supposed to be in from within my autoloader by using __NAMESPACE__ or some other such mechanism?

推荐答案

自动加载器将获得foo\bar\baz\Quux作为类名参数.

The autoloader will get foo\bar\baz\Quux as the class name argument.

命名空间名称定义
不合格名称
这是一个标识符 没有命名空间分隔符,例如Foo

Namespace name definitions
Unqualified name
This is an identifier without a namespace separator, such as Foo

合格名称
这是带有名称空间分隔符的标识符,例如 作为Foo \ Bar

Qualified name
This is an identifier with a namespace separator, such as Foo\Bar

完全限定的名称
这是带有名称空间分隔符的标识符 以名称空间分隔符(例如\ Foo \ Bar)开头. namespace \ Foo也是完全限定的名称.

Fully qualified name
This is an identifier with a namespace separator that begins with a namespace separator, such as \Foo\Bar. namespace\Foo is also a fully qualified name.

规则是:

所有不合格和合格的名称(不是完全合格的名称)是 根据当前的导入规则在编译过程中进行翻译.为了 例如,如果将命名空间A \ B \ C导入为C,则对C \ D \ e()的调用为 转换为A \ B \ C \ D \ e().

All unqualified and qualified names (not fully qualified names) are translated during compilation according to current import rules. For example, if the namespace A\B\C is imported as C, a call to C\D\e() is translated to A\B\C\D\e().

这篇关于自动加载和名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆