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: Php, Programming, Web Development
Related Items:
- Editing live sites and the power of __autoload() in PHP 5
- Comparing MySQL to Oracle
- Only time breeds success
- Invalid host attack on PHP websites
- PHP Live

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