1

I want to create a class of which I don't know the name. What is the best way to accomplish the following scenario in PHP?

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

Thanks.

Marc Wiest
  • 349
  • 3
  • 9
  • See this -> http://stackoverflow.com/questions/7131295/dynamic-class-names-in-php – Jesse Sep 27 '15 at 02:02
  • @Jesse If I'm not mistaking, the example you reference shows how to instantiate an object from a class that already exists. My class doesn't exist yet. I want to dynamically create it. – Marc Wiest Sep 27 '15 at 02:05
  • In that scenario, the way you are doing it is the way it is done from what I can tell. See the 3rd answer down and so on after that. General consensus for this is an eval -> http://stackoverflow.com/questions/1203625/dynamically-generate-classes-at-runtime-in-php – Jesse Sep 27 '15 at 02:08
  • @Jesse, thanks for trying to help me find a solution to this. I think I have to search a little while longer before I'll give in to this approach. I can't say I'm a big fan of what I'm looking at, there has to be a better way. – Marc Wiest Sep 27 '15 at 02:27
  • Agreed. Nothing wrong with research and a better approach to eval should always be examined. I +1d and starred this post as I am curious if someone comes up with an answer not using eval. – Jesse Sep 27 '15 at 02:29
  • The above wouldn't be all to bad if I now didn't have to write the entire class into the `$code` string. Do you happen to have an idea how I could "extent" the class once it's defined without creating an object of it? – Marc Wiest Sep 27 '15 at 02:53

1 Answers1

0

I just tested this and it works fine. And if you only need the class temporarily you can always throw an unlink() at the bottom. No exec() required.

<?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);
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
  • Thanks for your suggestion, but your approach seams crappier (pun intended) than mine. The heredoc syntax makes writing the class a bit easier, but opens more space for errors. – Marc Wiest Sep 27 '15 at 16:54
  • well, to be fair, creating a class on the fly seems pretty crappy in general considering the security risks you're taking, whether or not you use `eval`. good luck finding something you like though. – I wrestled a bear once. Sep 29 '15 at 12:20