Clean, Tidy and Flexible Function Variables

The thing about functions is… they grow. They start off small and cute and useful, but over time you start to notice their little shortcomings, so you make them bigger, better, and more flexible. Unfortunately, if you’re using PHP’s default method of passing functions, which is based on the sequence the functions are given (i.e. function example($variable1, $variable2, $etc)) , things can get a little messy. The more variables a function can handle, the harder it is to remember the sequence they have to follow. Not to mention PHP 5 doesn’t facilitate a way to skip variables. For example, this doesn’t work: example($variable1, , $variable3, $etc).

The solution is to pass your variables on in an array. Here’s the template that I use whenever I code a new function:

function example($args="") {
    $variable1 = $args['variable1']? $args['variable1'] : 'default';
}

And this is how you pass variables on to your function:

$args = array(
    'variable1' => 'value',
    'variable2' => 2,
    'variable3' => $etc
);
example($args);

And what’s more, if you have an existing function that you want to convert to taking an array, but don’t want to change all of your existing function calls, you can do something like this:

function example($args="", $variable2, $variable3) {
    if (is_array($args)) {
        $variable1 = $args['variable1']? $args['variable1'] : 'default';
        $variable2 = $args['variable2']? $args['variable2'] : 'default';
    } else{
        $variable1 = $args;
    }
}

Clean, tidy, and easy as pie. :)

Share and Enjoy:
  • Print
  • Digg
  • Google Bookmarks
  • email
  • StumbleUpon

Date: Monday, December 14th, 2009
Category: Web Dev

blog comments powered by Disqus
  • « Older Entries
  • Newer Entries »

Copyright © 2009 Rajeev Singh