开发者

How to create object from String?

开发者 https://www.devze.com 2022-12-16 10:36 出处:网络
I tried the code b开发者_开发百科elow: $dyn = \"new \". $className . \"(\" .$param1 . \", \". $param2 . \");\";

I tried the code b开发者_开发百科elow:

$dyn = "new ". $className . "(" .$param1 . ", ". $param2 . ");";
$obj = eval($dyn);

It compiles but it's null.

How can you instance object in PHP dynamicaly?


$class = 'ClassName';
$obj = new $class($arg1, $arg2);


If you really want to use eval - which chances are you shouldn't if you're this new to PHP ;) - you'd do something more like...

$dyn = "new ". $className . "(" .$param1 . ", ". $param2 . ");";
eval("\$obj = $dyn");


What are you actually trying to accomplish? eval would work, but its probably not a very good idea.

What you might want to do is implement a factory for your objects that take a string defining what class to load, and an optional array for the constructors parameters

0

精彩评论

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

关注公众号