具有别名的动态命名空间类 [英] Dynamic namespaced class with alias

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

问题描述

SO

使用命名空间创建动态对象时遇到问题. 这是名称空间代码:

I have an issue with dynamic object creation using namespaces. Here's namespace code:

namespace Foo
{
   class Bar
   {
   }
}

现在,我正在尝试使用以下方法创建类Bar的对象:

Now, I'm trying to create object of class Bar with:

include('namespace.php');
$sName  = 'Bar';
$sClass = '\\Foo\\'.$sName;
$rObj   = new $sClass; //correct object

一切顺利.但是,现在我想使用别名并执行类似的操作:

and everything going well with that. But, now I want to use alias and doing something like:

include('namespace.php');
use Foo as Baz;
$sName  = 'Bar';
$sClass0= '\\Foo\\'.$sName;
$sClass1= '\\Baz\\'.$sName;
$rObj   = new $sClass0; //correct object
$rObj   = new $sClass1; //Fatal error

而且我无法以这种方式实例化对象(并且通过全名访问仍然可以正常工作). 所以,我的问题是-是否可以通过别名以某种方式访问​​该类,如果可以,如何进行?使用$sClass1='Baz\\'.$sName时,我也尝试访问-没有成功.另外,我已经通过get_declared_classes()函数检查了声明的类,这表明我只有\Foo\Bar类(没有对别名的引用).

And I'm unable to instantiate an object such way (and accessing via full name still works well). So, my question is - is it possible to access the class via alias somehow, and, if yes, how? I've also tried to access when using $sClass1='Baz\\'.$sName - no success. Also, I've checked declared classes via get_declared_classes() function, it shows that I have only \Foo\Bar class (no reference to an alias).

我不确定是否很重要,但是我使用的是PHP 5.5版本.

推荐答案

仅解析器使用您的命名空间别名对每个文件中的类引用进行规范化.

Only the parser uses your namespace aliases to canonicalize the class references inside each of your files.

换句话说,它没有引入其他代码可以使用的某种全局别名.解析脚本后,将不再使用别名.

In other words, it doesn't introduce some kind of global alias that other code can use. Once your script has been parsed, the alias is no longer used.

手册中也对此行为进行了描述:

This behaviour is also described in the manual:

导入是在编译时执行的,因此不会影响动态类,函数或常量名称.

Importing is performed at compile-time, and so does not affect dynamic class, function or constant names.

这篇关于具有别名的动态命名空间类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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