Jump to content

New Instance with namespace from string?


AbydosGater

Recommended Posts

I have a list of classes in a database that I wish to load and instanciate.

 

I know this can be done with something along the lines of:

$class = $row['name'];
$instance = new $class;

 

Ive tried the above syntax which works fine, but I am doing this with __autoload() and namespaces, so I tried the following syntax:

 

use Plugin as foo\bar\Plugins;

$class = $row['name'];
$instance = new Plugin\$class;

 

But this just throws an unexpected T_VARIABLE error.

 

Can anyone help me out with creating new instance of a class from a string with namespaces?

 

Thanks,

Andy

Link to comment
https://forums.phpfreaks.com/topic/216252-new-instance-with-namespace-from-string/
Share on other sites

You would need to use a string to reference the class with its namespace

 

    $class = "namespace\of\the\\$class";

 

Also note that you won't be able to use the aliased name (Plugin\$class) like you want to, the full namespace path must be used (whether you like it or not  :-[ ).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.