J. Doe J. Doe - 3 years ago 170
PHP Question

PHP multi param function

I need a practical approach to pass multiple parameters to a function which is used globally over several scripts to dump a table from a database.

It accepts multiple parameters (with default values for each) and it depends on whether the scripts needs a specific option to be activated inside the function.

For example:

function dump_table($sumtotal=false, $countrows=false, $yadalada=false... etc){


The question is, if I have 10 different parameters and a script needs only parameter 10 to be true I must call something like this:

dump_table(false,false,false,false...., true)


So... Is there another way to make it easily scalable without the overhead in the function calls?

I though to use objects, but afaik It would involve a class and instance creation on every call.

Is there a way to make something like this in php (javascript-like style):

dump_table({opt1: true, opt10: true, opt99: true})


Or even

$options = { count: true, sumtotals: true };
dump_table($options);



  • Inside the function I would use something like
    property_exists
    to check which ones to set...



thx

Answer Source

You can use such approach:

function yourFunction(array $parameters = array()) {
   //here you should define all possible parameters with their defaults
   $param_1 = true;
   $param_2 = false;
   ...
   $param_10 = true;
   ...
   $param_N = 'whatever';

   //and now simply extract passed parameters
   extract($parameters, EXTR_OVERWRITE | EXTR_IF_EXISTS);
}

Usage:

yourFunction(['param_1' => false, 'param_10' => 'something']);

extract($parameters, EXTR_OVERWRITE | EXTR_IF_EXISTS) will overwrite default defined variables with those that would be passed through $parameters array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download