从变量创建类名 [英] Creating a class name from a variable

查看:136
本文介绍了从变量创建类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用PHP中的变量来定义类名。这是可能吗?

I would like to define the class name using variables in PHP. Is this possible?

让我解释一下。

我是一个小型自定义CMS,请为表名称配置前缀。因此,用户可以定义前缀,例如rc_。问题是,我有很多模型使用表名作为类。例如,如果我的表中的一个是 rc_posts ,模型将被调用

I am a small custom CMS that allows the end user to configure a prefix for the table names. So a user can define the prefix such as "rc_". The problem is, I have a lot of models that use the table name as the class. So for example, if one of my tables is rc_posts, the model will be called

class MyModel_Rc_posts extends MyModelController {
         // code here
}

有什么方法可以使用PHP中的变量定义一个类,而不使用 eval(),例如:

Is there any way to define a class using variables in PHP WITHOUT using eval() such as:

class MyModel_{$PREFIX}posts extends MyModelController {
// code here
}

我想避免eval的原因是因为这些类中的一些可以得到很长时间。建议。

The reason I want to avoid eval, is because some of these classes can get pretty long. Suggestions appreciated.

推荐答案

查看 class_alias - 它应该可以帮助您更清楚这一点!

Take a look at class_alias - it should help you make this even readable!

:你使用正常名称创建类,然后根据需要添加别名。别名可以是任何字符串,包括存储在变量中的字符串。

Just to make this clear: You create your class with a "normal" name, then add an alias name on demand. The alias name can be any string, this includes a string stored in a variable.

编辑

虽然我认为, class_alias()是要走的路,这里是一个例子,如何做没有它。

While I think, that class_alias() is the way to go, here is an example on how to do it without it.

从您的OQ:

class MyModel_Rc_posts extends MyModelController {
         // code here
}

现在

eval("class MyModel_{$PREFIX}posts extends MyModel_Rc_posts {};");

应该执行类似于 class_alias()

如果你需要 get_class()给你原来的(静态)类名,而不是别名。使用丑陋 eval() / extends 骗子你会得到动态名称。

Going this rout could be necessary, if you need get_class() later - on an aliased class, it will give you the original (static) classname, not the alias. With the ugly eval()/extends trick you get the dynamic name.

这篇关于从变量创建类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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