带有动态类名的 PHP 命名空间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4513366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP namespace with Dynamic class name
提问by DeaconDesperado
Wondering if anyone else has encountered this problem when utilizing the new ability to namespace classes using PHP 5.3.
想知道其他人在使用 PHP 5.3 的命名空间类的新功能时是否遇到过这个问题。
I am generating a dynamic class call utilizing a separate class for defining user types in my application. Basically the class definer takes an integer representation of types and interprets them, returning a string containing the classname to be called as the model for that user.
我正在生成一个动态类调用,使用一个单独的类在我的应用程序中定义用户类型。基本上类定义器采用类型的整数表示并解释它们,返回一个包含类名的字符串,作为该用户的模型。
I have an object model for the user's type with that name defined in the global scope, but I have another object with the same name for the user's editor in the Editor namespace. For some reason, PHP won't allow me to make a namespaced dynamic call as follows.
我有一个用户类型的对象模型,在全局范围内定义了该名称,但我在 Editor 命名空间中有另一个与用户编辑器同名的对象。出于某种原因,PHP 不允许我按如下方式进行命名空间动态调用。
$definition = Definer::defineProfile($_SESSION['user']->UserType);
new \Editor$definition();
The identical syntax works for calling the global basic object model in the global namespace and I use it this way reliably throughout the application.
相同的语法适用于在全局命名空间中调用全局基本对象模型,我在整个应用程序中以这种方式可靠地使用它。
$definition = Definer::defineProfile($_SESSION['user']->UserType);
new $definition();
This will correctly call the dynamically desired class.
这将正确调用动态所需的类。
Is there a reason the two would behave differently, or has dynamic calling for namespaces not been implemented in this manor yet as this is a new feature? Is there another way to dynamically call a class from another namespace without explicitly placing its name in the code, but from within a variable?
是否有原因两者的行为会有所不同,或者由于这是一项新功能,因此在此庄园中尚未实现对名称空间的动态调用?有没有另一种方法可以从另一个命名空间动态调用一个类,而无需将其名称显式地放在代码中,而是从变量中?
回答by ircmaxell
Well, just spell out the namespace in the string:
好吧,只需在字符串中拼出命名空间:
$definition = Definer::defineProfile($_SESSION['user']->UserType);
$class = '\Editor\' . $definition;
$foo = new $class();
And if it's a child namespace (as indicated in the comments), simply prepend the namespace with __NAMESPACE__
:
如果它是一个子命名空间(如注释中所示),只需在命名空间前面加上__NAMESPACE__
:
$class = __NAMESPACE__ . '\Editor\' . $definition;
So if the current namespace is \Foo\Bar
, and $definition
is "Baz", the resulting class would be \Foo\Bar\Editor\Baz
因此,如果当前命名空间是\Foo\Bar
,并且$definition
是“Baz”,则生成的类将是\Foo\Bar\Editor\Baz