Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to declare a php class with a variable name

Tags:

php

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:
http://us3.php.net/manual/en/keyword.class.php

thanks very much for your help

like image 599
toy Avatar asked Sep 15 '11 22:09

toy


1 Answers

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).

like image 66
JRL Avatar answered Oct 26 '22 23:10

JRL