ethanpil ethanpil - 2 years ago 127
PHP Question

PHP Function Arguments - Use an array or not?

I like creating my PHP functions using key=>value pairs (arrays) as arguments instead of individual parameters.

For example, I prefer:

function useless_func($params) {
if (!isset($params['text'])) { $params['text'] = "default text"; }
if (!isset($params['text2'])) { $params['text2'] = "default text2"; }
if (!isset($params['text3'])) { $params['text3'] = "default text3"; }
echo $params['text'].$params['text2'].$params['text3'];

And I don't like:

function useless_func($text = "default text", $text2 = "default text2", $text3 = "default text3") {
echo $text.$text2.$text3;

I had first seen things done this way extensively in the Wordpress codebase.

The reason I prefer arrays:

  • Function arguments can be provided in any order

  • Easier to read code / more self documenting (in my opinion)

  • Less prone to errors, because when calling a function I must investigate the proper array keys

I was discussing this with a co-worker and he says that it's useless and just leads to extra code and it's much harder to set the default values. Basically, he disagrees with me completely on all three points.

I am looking for some general advise and guidance from experts who might be able to provide insight: What's the better or more proper way to do this?

Answer Source

Well, it's kinda usefully. But for some arguments which is passing always it's better to use classic passing like function some($a1, $a2). I'm doing like this in my code:

function getSome(SomeClass $object, array $options = array())
    // $object is required to be an instance of SomeClass, and there's no need to get element by key, then check if it's an object and it's an instance of SomeClass

    // Set defaults for all passed options
    $options = array_merge(array(
        'property1' => 'default1',
        'property2' => 'default2',
        ... => ...
    ), $options); 

So, as you can see I like that code style too, but for core-arguments I prefer classic style, because that way PHP controls more things which should I, if I used the you code style.

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