2015-09-27 72 views
1

我想创建一个我不知道名称的类。在PHP中完成以下场景的最佳方式是什么?使用变量动态定义PHP类

$class_name = 'SomeClassName'; 
$code = "class {$class_name}_Control extends WP_Customize_Control {}"; 
eval($code); 

谢谢。

+0

请参阅本 - > http://stackoverflow.com/questions/7131295/dynamic-class-names-in-php – Jesse

+0

@Jesse如果我没有弄错,你引用的示例演示如何实例化一个来自已存在的类的对象。我的课程还不存在。我想动态地创建它。 – Marc

+0

在这种情况下,你做这件事的方式就是我所能说的。之后查看第三个回答,等等。一般共识这是一个评估 - > http://stackoverflow.com/questions/1203625/dynamically-generate-classes-at-runtime-in-php – Jesse

回答

0

我刚测试过它,它工作正常。如果你只是暂时需要上课,你总是可以在底部投一个unlink()。不需要exec()

<?php 

// your dynamic classname 
$fart = "poot"; 

// define your class, don't forget the "<?php" 
$class = <<<YOYOYOHOMIE 
<?php 
class $fart{ 
    public \$poop = "poop"; 
} 
YOYOYOHOMIE; 

// write the class to a file. 
$filename = "dynamicClass".time().".php"; 
$fh = fopen($filename,"w+"); 
fwrite($fh, $class); 
fclose($fh); 

// require the file 
require $filename; 

// now your dynamically generated class is available 
$tird = new $fart; 
echo "<pre>"; 
var_dump($tird); 
+0

感谢您的建议,但您的方法接缝crappier(双关语意)比我的。 heredoc语法使得编写该类变得更容易一点,但为错误打开更多空间。 – Marc

+0

好,说句公道话,动态创建一个类似乎一般漂亮蹩脚考虑安全隐患,你正在做,无论是否使用'eval'。祝你好运,找到你喜欢的东西。 –