Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic namespaced class with alias

Tags:

namespaces

php

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.

like image 482
Alma Do Avatar asked Apr 24 '26 17:04

Alma Do


1 Answers

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.

like image 163
Ja͢ck Avatar answered Apr 26 '26 06:04

Ja͢ck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!