Book HomePHP CookbookSearch this book

7.13. Creating a Class Dynamically

7.13.1. Problem

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

7.13.2. Solution

Use eval( ) with interpolated variables:

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.

7.13.4. See Also

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



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.