Why are configuration arrays acceptable parameters in PHP and Javascript? Why are configuration arrays acceptable parameters in PHP and Javascript? php php

Why are configuration arrays acceptable parameters in PHP and Javascript?


In my opinion, a lot of these functions are climbing in the number of arguments they accept, over 10 is not uncommon. Even if you do optional parameters, you still have to send them in order.

Consider a function like:

function myFunc(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13){    //...}

Say you want to use arguments 3 and 11 only. Here is your code:

myFunc(null, null, null, 'hello', null, null, null, null, null, null, null, 'world');

Wouldn't you rather just:

myFunc({    a3 : 'hello',     a11 : 'world' });

?


There are a couple of reasons for this.

The first is that not all argument lists have a natural order. If there is a use-case to only supply the 1st and 6th argument, now you have to fill in four default placeholders. Jage illustrates this well.

The second is that it's very hard to remember the order the arguments must occur in. If you take a series of numbers as your arguments, it's unlikely to know which number means what. Take imagecopyresampled($dest, $src, 0, 10, 0, 20, 100, 50, 30, 80) as an example. In this case, the configuration array acts like Python's named arguments.


The major reason is that those particular languages simply do not support having multiple calling conventions for the same function name. I.E. you can't do the following:

public function someFunc(SomeClass $some);public function someFunc(AnotherClass $another);public function someFunc(SomeClass $some, AnotherClass $another);

So you must find another way to create simpler ways to pass your variables around, in PHP we end up with someFunc(array('some'=>$some, 'another'=>$another)) because it is the only convenient way. In JavaScript we end up using objects, which isn't as bad: someFunc({some: something, another: anotherthing})