Razvan Zamfir
Razvan Zamfir

Reputation: 4614

What is elegant solution for a PHP function with a lot of parameters?

I need to create a function that would insert user data into a "medical_records" table that has about 30 fields.

So the "classic" solution is writing something like:

function insert_medical_records($param1, $param2,..., $param30) {
    // code here
}

But of coarse, such code writing is prone to errors and not elegant at all.

I thought of better solution like creating an array of parameters and passing its values to the function, but I don't quite know a valid syntax for that.

Or maybe there is a better solution then this altogether?

Thank you!

Upvotes: 1

Views: 729

Answers (2)

Sammitch
Sammitch

Reputation: 32232

How about:

class MedicalRecords {
    /* code here */
}

function insert_medical_records(MedicalRecords $mr) {
    /* more code here */
}

and now you can add logic to do thing like validation on the records to the object itself and better seperate your code's concerns along more logical lines.

Upvotes: 0

Bedo
Bedo

Reputation: 937

Since php has a soft type control, you can just give your function one input parameter. That parameter will be an array or an object.

In case of an array:

function insert_medical_records($input_array) {
    // Here you can use $input_array['param1'], $input_array['param2'],
}

Before calling the function, you need to populate the array, something like:

$input_array['param1'] = "your param 1 value";
$input_array['param2'] = array('a' => 1, 'b' => 2);

insert_medical_records($input_array);

I would also suggest you to check the content of the input variable of the function:

function insert_medical_records($input_array) {
  if (!isset($input_array['param1'])) {
     // manage your error
     return;
  }
  // Everything is ok. Do your stuff here...
}

Instead of isset, you should also consider using empty, is_array or array_key_exists. This it's up to your specific situation.

The solution using Object instead of Array is really similar. You define attributes such as $input_object->param1.

Upvotes: 2

Related Questions