Dynamic namespaced class with alias

本秂侑毒 提交于 2020-01-11 09:35:08

问题


SO,

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

namespace Foo
{
   class 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

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).

I'm not sure if it matters, but I'm using PHP 5.5 version.


回答1:


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.



来源:https://stackoverflow.com/questions/18318582/dynamic-namespaced-class-with-alias

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!