问题
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