Pick Brains - Straight answers on your questions about money, or life in general. Improve your life with tips, money ideas and other interest items.

Front Page > Articles > Dynamically load a class in PHP

Dynamically load a class in PHP

Recently I visited a PHP forum where a user was asking how to "Dynamically Load A Class" in PHP using a variable.

He proceeded to make an invalid example like:

$module = new Mod_{$tmp_Name} ();

It is common in PHP to allow a PHP script to be extended just by adding extra classes. Theses classes are often found automatically and loaded from a variable in a string.

The problem is the solution that the user came up with is the most often used, but most insecure method. It was to use the eval function:

$toRun = "\$module = new Mod_{$toPass} ();";
eval ($toRun);

The eval command is a very powerful command. Used in correctly it can be a vary large security hole in your website.

The best method of dynamically loading a class in PHP that should have been used is:

$toRun = 'MyClass';
$instance = new $toRun();

Tags: , ,

Related Items:

Comments / Replies

  • Anand Says:
    25 September, 2008 at 2:12 pm

    Also one more comment on eval(). Many hosting company is not support this eval function. So this reduce your code portability between hosting servers So be careful on this

Add Comment / Reply

You can not use HTML in this field. If you wish to add a URL, write the full URL including http://