Clément Laffitte Clément Laffitte - 2 years ago 128
PHP Question

PHP - Call class like call_user_func

I have 2 variables :

$class : contains the name of the class
$params : contains the parameters to initialize the class like ["key1" => "value1", "key2" => "value2"]

And I want to call a class like the function call_user_func() do with functions

ie :

$classObject = call_class($class, $params);
// Do the same that:
$classObject = new $class("value1", "value2");

Answer Source

One option would be to use array argument unpacking, if you're running PHP >= 5.6:

$classObject = new $class(...$params);

Another would be to use Reflection

$reflection = new ReflectionClass($class);
$classObject = $reflection->newInstanceArgs($params);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download