November 11, 2008
Faking named parameters in PHP

marco:

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):

<?php
function my_function(
    $id,
    $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:

<?php
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:

<?php
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.

This same hack/trick has been used in perl for ages… but thank fully we may get named parameters in perl 6, personally I prefer to use this technique in larger projects which makes the code more self explanatory. I hate reading code like this:

sub my_sub_routine($$$$){
    my first_param = @_[0];
    my second_param = @_[1];
    my third_param = @_[2];
    my fourth_param = @_[3];
}

I fill bad every time I have to write things like this...

7:59pm  |   URL: http://tmblr.co/Zn5Hby3XqMX
  
Filed under: code perl development 
  1. mandel reblogged this from marco and added:
    This same hack/trick has been used in perl...ages… but thank fully we may get named...
  2. marco posted this