Reputation: 76240
How can I call a object constructor passing an array of parameters so that having:
$array = array($param1, $param2);
I'll be able to call
$abc = new Abc($param1, $param2);
considering that I don't know how many parameters could be set in the array.
Is there something like call_object('Abc', array($param1, $param2))
?
Upvotes: 11
Views: 18138
Reputation: 211
How about using ... (splat operator)?
$array = array($param1, $param2);
$abc = new Abc(...$array); // equal to: new Abc($param1, $param2)
PHP 5.6 is required.
Upvotes: 21
Reputation: 237817
The ideal is to define your constructor to take an array.
If you can't do that, there is a possible workaround. If all parameters to the constructor are optional, you could do something like this with call_user_func_array
:
$obj = new Abc;
call_user_func_array(array($obj, '__construct'), $array);
This results in your constructor being run twice: once with no parameters, and once with those in the array. You'll have to decide whether this is suitable for your application.
Upvotes: 4
Reputation: 270599
Assuming you are able to modify your objects' constructors, a pattern like this isn't uncommon, but requires associative arrays as input:
class Abc {
public $prop1;
public $prop2;
public function __construct($params) {
if (is_array($params)) {
$this->prop1 = isset($params['prop1']) ? $params['prop1'] : NULL;
$this->prop2 = isset($params['prop2']) ? $params['prop2'] : NULL;
}
}
}
// Created as:
$params = array('prop1'=>12354, 'prop2'=>54321);
$abc = new Abc($params);
Upvotes: 3
Reputation: 1047
The best way is to use an array or object that stores the arguments and you just pass that array/object
Another way would be using Reflection ( https://www.php.net/Reflection ) using newInstanceArgs ( https://www.php.net/manual/de/reflectionclass.newinstanceargs.php )
Upvotes: 7