Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array of parameters to object constructor

Tags:

oop

php

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))?

like image 790
Shoe Avatar asked Dec 16 '11 14:12

Shoe


2 Answers

How about using ... (splat operator)?

$array = array($param1, $param2);
$abc = new Abc(...$array); // equal to: new Abc($param1, $param2)

PHP 5.6 is required.

like image 160
augusthur Avatar answered Nov 18 '22 13:11

augusthur


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 ( http://de2.php.net/Reflection ) using newInstanceArgs ( http://de2.php.net/manual/de/reflectionclass.newinstanceargs.php )

like image 7
DarkDevine Avatar answered Nov 18 '22 13:11

DarkDevine