Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

how to declare a php class with a variable name

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...