views:

1430

answers:

2

I know this question sounds rather vague so I will make it more clear with an example:

$var = 'bar';
$bar = new {$var}Class('var for __construct()'); //$bar = new barClass('var for __construct()');

This is what I want to do. How would you do it? I could off course use eval() like this:

$var = 'bar';
eval('$bar = new '.$var.'Class(\'var for __construct()\');');

But I'd rather stay away from eval(). Is there any way to do this without eval()?

+7  A: 

Put the classname into a variable first:

$classname=$var.'Class';

$bar=new $classname("xyz");

This is often the sort of thing you'll see wrapped up in a Factory pattern - there's an example in the PHP manual.

Paul Dixon
This is how I do it. Note that from within classes you can use parent and self.
Ross
Thank you very much.
Pim Jager
On a similar note, you can also do $var = 'Name'; $obj->{'get'.$var}();
Mario
Good point, though that only works for method calls and not constructors
Paul Dixon
+1  A: 
class Test {

public function yo() {
 return 'yoes';
}
}

$var = 'Test';

$obj = new $var();
echo $obj->yo(); //yoes
zalew