使用“全局命名空间"; [英] use "global-namespace";

查看:90
本文介绍了使用“全局命名空间";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道是否有一种方法可以使用"use"关键字使类的行为像在全局名称空间中一样,因此该类只能从类外部作为名称空间类起作用. 像这样:

I just wonder if there's a way to make a class behave as if it is in global namespace using a "use" keyword, so this class would behave as namespaced class only from outside of the class. Something like:

namespace wherever\somewhere\deep\deep\inside;
use \; // root namespace.. note: this doesn't work
class stuff{
//....
}

有人吗?

推荐答案

使用全局名称空间无法按您期望的方式工作.

Using the global namespace won't work the way you expect.

默认情况下,您可以通过添加反斜杠来引用全局命名空间的类,例如$x = new \PDO(...);.尝试use \不会改变这一点.

By default, you can reference a globally namespaced class by adding a backslash -- eg $x = new \PDO(...);. Trying to use \ won't change that.

如果要从全局命名空间的类中删除反斜杠,则需要专门地每个use.在带名称空间的PHP中,任何不具有名称空间的类引用都假定位于当前名称空间中,除非由use语句显式引用.

If you want to drop the backslash from globally namespaced classes, you need to use each of them specifically. In namespaced PHP, any class reference that doesn't have a namespace is assumed to be in the current namespace, unless it is explicitly referenced by a use statement.

例如:

use \PDO, \SplFileObject;

现在我们可以在不加反斜杠的情况下调用new PDO(...)new SplFileObject().但是其他不在use中的全局类仍然需要反斜杠.

now we can call new PDO(...) or new SplFileObject() without the backslash. But other global classes that aren't in the use would still need the backslash.

这篇关于使用“全局命名空间";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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