Search code examples
phpcoding-stylelanguage-comparisons

Passing an array for setting variable


I often see this idiom when reading php code:

public function __construct($config)
{
    if (array_key_exists('options', $config)) {
       ...
    }
    if (array_key_exists('driver_options', $config)) {
        ...
    }
}

Here I am concern with the way the parameter is used. If I were in lisp I would do:

(defun ct (&key options driver_options) 
       (do-something-with-option-and-driver_option))

But since I am in PHP I would rather have a constructor that take a list of parameter and let them be null if there a not require.

So what do you guys think about having an array as parameter in other to do some initialization-or-whatever?

In other to answer you have to take in account the point of view of the user of the function and the designer of the API.


Solution

  • Personally, I dislike that idiom. I prefer to have a long parameter list instead, if necessary.

    The problem is that I can't know the elements the array can't take by looking at the function signature. On top of that, the implementations almost never check if there's any key that's not recognized, so if I mispell an array key, I get no warning.

    A better alternative would be passing a configuration object. At least, there the IDE can provide me hints on the available configuration objects and the calculated default values for missing options can be moved away from the constructor you show to the getters in the configuration object. The obvious alternative is to provide setters for the several configuration options; though this doesn't help for the required ones for each no default can be provided.