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.

6
  • See this -> stackoverflow.com/questions/7131295/dynamic-class-names-in-php Commented Sep 27, 2015 at 2: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. Commented Sep 27, 2015 at 2: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 -> stackoverflow.com/questions/1203625/… Commented Sep 27, 2015 at 2: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. Commented Sep 27, 2015 at 2: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. Commented Sep 27, 2015 at 2:29

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.