7.12. Creating a Class Dynamically

Problem

You want to create a class, but you don’t know everything about it until your code is executed.

Solution

Use eval( ) with interpolated variables:

eval("class van extends $parent_class {
    function van() {
        \$this->$parent_class();
    }
};");

$mystery_machine = new van;

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.

See Also

Recipe 7.14 to instantiate an object dynamically; documentation on eval( ) at http://www.php.net/eval.

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.