开发者

Importing variable namespaces

Would it be pos开发者_如何学编程sible to import namespaces using a variable like this:

$namespace = 'User\Authorization\Certificate';
use $namespace;

Obviously this won't run as use statement expects a constant but is there a workaround?

Edit: Discovered a gem (only in PHP > 5.3): class_alias($namespace, alias); which does pretty much the same thing with use User\Authorization\Certificate as alias; so will be using that.


While it isn't possible to pass a namespace in a variable to use, you can place the namespace and the expected "short" class name in a variable and use that in most places where you'd need it, like invoking new.

$namespace = '\foo\bar';
$class = 'baz';
$fully_qualified = $namespace . '\\'. $class; // \foo\bar\baz
$a_foo_bar_baz = new $fully_qualified(...);
var_dump( $a_foo_bar_baz instanceof $fully_qualified ); // true


No, PHP expects the use to follow a namespace, not an expression (which includes not a constant). See Using namespaces: Aliasing/Importing.

However if you change the PHP code on the fly before executing it in some kind of aggregation or compilation phase within your system, you could replace the text with some variable data which looks static enough for PHP then.

But I have no idea if your system is capable of doing so. I could imagine some stream wrapper or stream filter doing this on the fly. It could transparently take care of inserting the variable namespace name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜