Reputation: 106
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");
Upvotes: 1
Views: 96
Reputation: 2397
call_user_func_array lets you invoke the class methods.
<?php
class Foo {
public function bar($param1, $param2) {
echo $param1.$param2;
}
}
$className = 'Foo';
call_user_func_array(array(new $className, 'bar'), array('Hello', 'World !'));
Upvotes: 1
Reputation: 212522
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);
Upvotes: 2