本文介绍了如何使用其他命名空间中的对象以及如何在PHP中导入命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两行之间的主要区别是什么?

What is the main difference between these two lines?:

$obj = new ArrayObject();

&

$obj = new \ArrayObject();

当我使用第一行时,出现错误:"Fatal error: Class '\Foo\Bar\ArrayObject' not found...",我不太确定为什么会收到此错误?第二行似乎已经解决了问题.

When I used the first line I got an error: "Fatal error: Class '\Foo\Bar\ArrayObject' not found..." and I am not too sure as to why I got this error? The second line seemed to have fixed the problem.

推荐答案

如果使用:

$obj = new ArrayObject();

表示在当前名称空间中定义了ArrayObject.您可以在全局名称空间(当前范围中未定义名称空间)中,或者在与当前范围相同的名称空间中定义ArrayObject时,使用此语法(示例Foo\Bar).

it means that ArrayObject is defined in current namespace. You can use this syntax where you are in global namespace (no namespace defined in current scope) or if ArrayObject is defined in the same namespace as current scope (example Foo\Bar).

如果您使用:

$obj = new \ArrayObject();

这意味着ArrayObject是在全局名称空间中定义的.

it means that ArrayObject is defined in global namespace.

在您的示例中,您可能具有类似的代码:

In your example you probably have code something like that:

namespace Foo\Bar;

$obj = new ArrayObject();

该操作无效,因为您尚未在Foo\Bar命名空间中定义ArrayObject.

It won't work because you haven't defined ArrayObject in Foo\Bar namespace.

上面的代码与:

namespace Foo\Bar;

$obj = new \Foo\Bar\ArrayObject();

如果ArrayObject是在全局名称空间中定义的(可能是您的情况),则需要使用代码:

And if ArrayObject is defined in global namespace (as probably in your case) you need to use code:

namespace Foo\Bar;

$obj = new \ArrayObject();

强调在Foo\Bar名称空间中未定义ArrayObject

to accent that ArrayObject is not defined in Foo\Bar namespace;

另一件事-如果您在当前名称空间的许多地方使用ArrayObject,则每次添加反斜杠时可能都不太方便.这就是为什么您可以导入名称空间,以便可以使用更简单的语法的原因:

One more thing - if you use ArrayObject in many places in your current namespace it might be not very convenient to add each time leading backslash. That's why you may import namespace so you could use easier syntax:

namespace Foo\Bar;

use ArrayObject;

$obj = new ArrayObject();

如您所见,

在创建要从全局名称空间导入ArrayObject的对象之前添加了use ArrayObject;.使用use不需要添加(也不应该)添加前导反斜杠,但是它的作用与use \ArrayObject;相同,因此上述代码在逻辑上等效于:

As you see use ArrayObject; was added before creating object to import ArrayObject from global namespace. Using use you don't need to add (and you shouldn't) add leading backslash however it works the same as it were use \ArrayObject; so above code is equivalent logically to:

namespace Foo\Bar;

use \ArrayObject;

$obj = new ArrayObject();

但是,正如我所说的,不应在导入名称空间时使用反斜杠.为此引用PHP手册:

however as I said leading backslash in importing namespaces should not be used. Quoting PHP manual for that:

这篇关于如何使用其他命名空间中的对象以及如何在PHP中导入命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-10 11:47