开发者

Create class with class name

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 thi开发者_StackOverflow中文版s in PHP? If possible, I'd also like to know if this is possible in Java.

Cheers! thanks in advance.


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( );


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);


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 ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜