How to create an object from String?

I tried the code below:

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

It compiles, but is null.

How can you instantiate an object in PHP dynamically?

+3
source share
3 answers
$class = 'ClassName';
$obj = new $class($arg1, $arg2);
+19
source

If you really want to use eval- what chances you should not, if you are new to PHP;) - you would do something more ...

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

? eval , , , .

, factory , , , ,

+1

Source: https://habr.com/ru/post/1728792/


All Articles