Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata