6

is there a way in php
to declare a class using a variable
ie (this doesnt work - but its here to give you an idea of my intention):

$myname = "the_class";
class $myname {
 ...
}

i also tried:

define("MYNAME","the_class");
class MYNAME{
 ...
}

and i tried:

$myname = "the_class";
class $$myname {
 ...
}

this doesnt really help:
http://php.net/manual/en/language.variables.scope.php

nor does this:
https://www.php.net/manual/en/keyword.class.php

thanks very much for your help

6
  • 12
    Why on Earth would you want to do that? Commented Sep 15, 2011 at 22:48
  • perhaps if you told us what you plan to do with it, we may find a better way to accomplish your end goal. I can't imagine a reason why this would be needed... Commented Sep 15, 2011 at 22:50
  • I would appear that your are defining $myname as a String, Not a class. Can one variable point to two objects? This is like a (math) function 1x -> 2ys Commented Sep 15, 2011 at 22:51
  • 6
    +1: I'm getting tired of these rabid downvoters who can't even bother to explain themselves. The question is valid. If you disagree with that the question asker is trying to do... simply answer the question then provide an alternative. As for why you would want to do such a thing... well, it has its uses. Commented Sep 15, 2011 at 23:11
  • 1
    Agree with @Fake Code Monkey Rashid. One valid case I can infer from his logic is if hes is trying to mock or stub something. Maybe he's working on a test suite? His question was clear and straightforward and even "showed his work" with research notes.. doesn't warrant downvote imho. Commented Sep 15, 2011 at 23:20

2 Answers 2

7

Sure, use php to write to a file with the name you want, then require that file. You could also use eval, e.g. something like: eval("class $myname { ... };");

For more complicated cases, use a library such as Zend's CodeGenerator (example here).

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

Comments

0

Please don't up/downvote this response or mark it as the answer.

Eugen Rieck's answer is the best one, but got buried in the comments.

The answer he linked to shows how to use class_alias() to name a class to a define. This is useful if you are writing a library class and wish to let the user name it whatever they want, for example by setting a define in a config file.

So if you are writing a library containing MyLibraryClass, you could let the user name it to something like LC for conciseness so they can write LC::someFunction() or LC->someFunction instead of having to write the whole thing out.

Comments

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.