0

I'm trying to figure a way to do create a class with only the class's name in PHP.

E.g.:

$class = "MyClass";

if(class_exists($class))
$unit = new $class($param1, $param2);
else
$unit = new Unit($param1, $param2);

Is there a way to do this in PHP? If possible, I'd also like to know if this is possible in Java.

Cheers! thanks in advance.

Daniel
  • 30,896
  • 18
  • 85
  • 139
willium
  • 2,048
  • 5
  • 25
  • 34
  • For java, see [this](http://stackoverflow.com/questions/1268817/create-new-class-from-a-variable-in-java). – Mac Sep 10 '11 at 05:02
  • Also, for PHP see [this](http://stackoverflow.com/questions/1377052/can-php-instantiate-an-object-from-the-name-of-the-class-as-a-string). – Mac Sep 10 '11 at 05:11

3 Answers3

1

I don't know about PHP (haven't used it in years), but in Java you can do:

MyClass obj = (MyClass) Class.forName("MyClass").newInstance( );
Mac
  • 14,615
  • 9
  • 62
  • 80
0

you can use double $ signs in PHP to make a variable well.. variable.

i.e.

$$class($param1,$param2);

I have not come across such a capability in Java.

Note: you probably don't want to call your class "class" as it is a reserved word ;)

Ben
  • 1,292
  • 9
  • 17
0

Yep, it should work fine in PHP. I would write that like this in order to avoid duplicating all the parameters to the constructor (if they are the same, of course):

$class = 'MyClass';
if (! class_exists($class)) {
    $class = 'Unit';
}
$unit = new $class($param1, $param2);
redShadow
  • 6,687
  • 2
  • 31
  • 34