沃梦达 / 编程问答 / php问题 / 正文

具有动态类名的 PHP 命名空间

PHP namespace with Dynamic class name(具有动态类名的 PHP 命名空间)

本文介绍了具有动态类名的 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.

我有一个用户类型的对象模型,该名称在全局范围中定义,但我在 Editor 命名空间中有另一个同名的用户编辑器对象.出于某种原因,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;

因此,如果当前命名空间是 FooBar,并且 $definition 是Baz",则生成的类将是 FooBarEditor巴兹

So if the current namespace is FooBar, and $definition is "Baz", the resulting class would be FooBarEditorBaz

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

本文标题为:具有动态类名的 PHP 命名空间

基础教程推荐