Forum Moderators: coopster

Message Too Old, No Replies

Dynamically Load A Class

How do you dynamically load a class using a variable?

         

Sekka

1:10 pm on Jul 16, 2006 (gmt 0)

10+ Year Member



Hi,

I want to dynamically load a class using a variable, e.g.

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

Where $tmp_Name is the name of the class.

Is there anyway to achieve this kind of thing?

Thank you.

eelixduppy

1:19 pm on Jul 16, 2006 (gmt 0)



I'm not sure if this can be done, although if it can, I assume that it follows the same concept as variable variables [php.net]. This works for function names too. I would give it a try and play around with it to see what you can achieve.

Best of luck!

Sekka

1:22 pm on Jul 16, 2006 (gmt 0)

10+ Year Member



What about using eval ()?

[uk2.php.net...]

Sekka

1:46 pm on Jul 16, 2006 (gmt 0)

10+ Year Member



Bingo! This works,

class Mod_Test {

function Mod_Test () {

echo "Running<br>";

}

function test2 () {

echo "Running2<br>";

}

}

$toPass = "Test";

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

eval ($toRun);

// Echos "Running"

$module -> test2 ();

// Echos "Running 2"

eelixduppy

2:05 pm on Jul 16, 2006 (gmt 0)



Nice work! Glad you got it ;)

thing3b

9:27 pm on Jul 18, 2006 (gmt 0)

10+ Year Member




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

Eval() should not be used in situations like this. Unless a lot of pre-checking of variables is done, eval() leads to security flaws in PHP scripts and the possibility of your PHP script getting hacked.

Only in rare cases should eval be used, and I have avoid these cases as much as possible. Eval() is evil.

Instead, what I do is:

class Mod_Test {
function Mod_Test () {
echo "Running<br>";
}
function test2 () {
echo "Running2<br>";
}
}

$toPass = 'Test';
$classToLoad = 'Mod_' . $toPass;
$module = new $classToLoad();
$module -> test2 ();

Sekka

9:39 pm on Jul 18, 2006 (gmt 0)

10+ Year Member



Hrm. I tried this initially but couldn't get it to work.

I did realise using eval() would cause a major security hole so I did make sure that was being passed to the eval() statement was properly checked and verified.

Thank you very much.