I’m : a programmer, writer, podcaster, geek, and coffee enthusiast.

Faking named parameters in PHP

Here’s a short technique for faking Ruby’s cool named-parameter ability. It’s useful when you have a function that takes a lot of optional arguments, and you occasionally want to specify a few of the middle values without specifying all of the preceding values (or knowing how many there are). It also helps code readability if you’re willing to make the slight performance sacrifice — and since you’re writing in a dynamic language, that’s probably true.

The function (note the use of extract):

function my_function(
    $start = 0,
    $limit = 10,
    $filter = false,
    $include_duplicates => false,
    $optimize_fetch => false,
    $cache = false
) {
    if (is_array($id)) extract($id, EXTR_IF_EXISTS);

    /* ... */

Calling it the old way still works perfectly fine as long as the first parameter isn’t normally supposed to be an array:

my_function(1, 0, 10, false, false, false, true);

But imagine how helpful that is when browsing this code 6 months later. Now, compare that with calling it the new way:

my_function(array('id' => 1, 'cache' => true));

Obviously, the function can have a lot more arguments, and this approach makes a lot more sense when it does.

It’d be great if PHP at least supported a compact or automatic array-literal syntax so we could avoid array(...) everywhere, but the developers really don’t like that idea.