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();