导入变量名称空间 [英] Importing variable namespaces
问题描述
是否可以使用这样的变量导入名称空间:
Would it be possible to import namespaces using a variable like this:
$namespace = 'User\Authorization\Certificate';
use $namespace;
很明显,这不会像use
语句所期望的那样运行,但是有解决方法吗?
Obviously this won't run as use
statement expects a constant but is there a workaround?
发现了一个gem(仅在PHP> 5.3中):class_alias($namespace, alias);
与use User\Authorization\Certificate as alias;
具有几乎相同的功能,因此将使用它.
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.
推荐答案
虽然无法将变量中的名称空间传递给use
,但您可以放置名称空间和预期的在变量中使用短"类名,并在大多数需要的地方使用它,例如调用new
.
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
这篇关于导入变量名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!