Reputation: 421
I need to create a new object which class is named for example 'Statistics1' - the '1' I got in a variable, so I need something like this:
$table = new Statistics${$mode};
It doesn't work. For variable in variables I use:
$var = ${"text" . $second_var};
But this time it's not a variable.
Upvotes: 0
Views: 61
Reputation: 15454
Class name could be an variable since PHP5.3
Changed: It's now possible to reference the class using a variable (e.g., echo $classname::constant;). The variable's value can not be a keyword (e.g., self, parent or static).
So sample code could looks like this.
class foo1
{}
$one = 1;
$class_name = 'foo' . $one;
$bar = new $class_name;
var_dump($bar);
Upvotes: 3
Reputation: 48284
I prefer reflection, because it's easier to catch exceptions:
$reflector = new ReflectionClass('Statistics'.$mode);
$table = $reflector->newInstance($arg1, $arg2);
Upvotes: 3