Syncrat - An article website that focuses on Music, Dating & Relationships and Business & Money. Learn about music, improve your dating or learn to make your money go further.

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

The address of your website or social networking page. Make sure that you include http://
You can not use HTML in this field. If you wish to add a URL, write the full URL including http://
 

This website follows the ideas of the No Nofollow, I Follow, DoFollow, No-NoFollow movement. Leave a helpful comment and you will get a link without NoFollow (U Comment, I Follow).

Web Hosting

If you are looking for web hosting then I would recommend my current web host. They have been good to me, suiting both beginners and advanced users.

Advertising

Using a transparent and trusted advertising network always helps to generate more revenue on a website. One of the networks I use achieves this more than the others.

Donations

If you would like to help pay the web hosting bill for this site, you can donate through my host

Your Ad Here

Web Hosting

If you are looking for web hosting then I would recommend my current web host. They have been good to me, suiting both beginners and advanced users.

Advertising

Using a transparent and trusted advertising network always helps to generate more revenue on a website. One of the networks I use achieves this more than the others.

Donations

If you would like to help pay the web hosting bill for this site, you can donate through my host