0

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.

2
  • exact duplicate stackoverflow.com/questions/7438324/… Commented Sep 1, 2012 at 18:27
  • Code smell detected: Why would you need to tie the domain object name to the table name if both are completely different: One is storage, the other is domain model. =\ If you really want this, you should have Table Data Gateway with a property representing the table name. Commented Sep 1, 2012 at 21:21

1 Answer 1

3

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:

class MyModel_Rc_posts extends MyModelController {
         // code here
}

Now

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

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 ugly eval()/extends trick you get the dynamic name.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. I will give this a shot and reply back!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.