Recipe 7.13 Creating a Class Dynamically
7.13.1 Problem
7.13.2 Solution
eval("class van extends $parent_class {
function van() {
\$this->$parent_class();
}
};");
$mystery_machine = new van;
7.13.3 Discussion
While it's okay in PHP to use variable names to call functions
or create objects, it's not okay to define functions and classes in a similar
manner:
$van( ); // okay
$van = new $parent_class // okay
function $van( ) {}; // bad
class $parent_class {}; // bad
Trying to do either of the last two examples results in a
parser error because PHP expects a string, and you supplied a variable.
So, if you want to make a class named $van and you
don't know beforehand what's going to be stored in $van, you need to
employ eval( ) to do your dirty work:
eval("class $van {};");
There is a performance hit whenever you call eval( ),
so high traffic sites should try to restructure their code to avoid this
technique when possible. Also, if you're defining your class based on input from
users, be sure to escape any potentially dangerous characters.