I would like to define the class name using variables in PHP. Is this possible?
Let me explain.
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
}
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
}
The reason I want to avoid eval, is because some of these classes can get pretty long. Suggestions appreciated.
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.
Edit
While I think, that
class_alias()is the way to go, here is an example on how to do it without it.From your OQ:
Now
should do something very similar to
class_alias().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 uglyeval()/extendstrick you get the dynamic name.