Reputation: 101
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
Upvotes: 6
Views: 1771
Reputation: 4823
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.
Upvotes: 0
Reputation: 77993
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).
Upvotes: 7