具有动态类名称的PHP名称空间 [英] PHP namespace with Dynamic class name

查看:85
本文介绍了具有动态类名称的PHP名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道是否有人在使用新功能通过PHP 5.3对类进行命名空间时会遇到此问题.

Wondering if anyone else has encountered this problem when utilizing the new ability to namespace classes using 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.

我有一个用于用户类型的对象模型,其名称在全局范围内定义,但是在编辑器"命名空间中,我还有另一个与用户的编辑器名称相同的对象.由于某些原因,PHP不允许我进行如下命名空间的动态调用.

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.

$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?

推荐答案

好吧,只需在字符串中拼出命名空间即可:

Well, just spell out the namespace in the string:

$definition = Definer::defineProfile($_SESSION['user']->UserType);
$class = '\\Editor\\' . $definition;
$foo = new $class();

如果它是子名称空间(如注释中所示),只需在名称空间前添加__NAMESPACE__:

And if it's a child namespace (as indicated in the comments), simply prepend the namespace with __NAMESPACE__:

$class = __NAMESPACE__ . '\\Editor\\' . $definition;

因此,如果当前名称空间是\Foo\Bar,并且$definition是"Baz",则结果类将是\Foo\Bar\Editor\Baz

So if the current namespace is \Foo\Bar, and $definition is "Baz", the resulting class would be \Foo\Bar\Editor\Baz

这篇关于具有动态类名称的PHP名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆