home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomePHP CookbookSearch this book

6.5. Using Named Parameters

6.5.3. Discussion

While using named parameters makes the code inside your functions more complex, it ensures the calling code is easier to read. Since a function lives in one place but is called in many, this makes for more understandable code.

When you use this technique, PHP doesn't complain if you accidentally misspell a parameter's name, so you need to be careful because the parser won't catch these types of mistakes. Also, you can't take advantage of PHP's ability to assign a default value for a parameter. Luckily, you can work around this deficit with some simple code at the top of the function:

function image($img) {
    if (! isset($img['src']))    { $img['src']    = 'cow.png';      }
    if (! isset($img['alt']))    { $img['alt']    = 'milk factory'; }
    if (! isset($img['height'])) { $img['height'] = 100;            }
    if (! isset($img['width']))  { $img['width']  = 50;             }
    ...
}

Using the isset( ) function, check to see if a value for each parameter is set; if not, assign a default value.

Alternatively, you can write a short function to handle this:

function pc_assign_defaults($array, $defaults) {
    $a = array( );
    foreach ($defaults as $d => $v) {
        $a[$d] = isset($array[$d]) ? $array[$d] : $v;
    }

    return $a;
}

This function loops through a series of keys from an array of defaults and checks if a given array, $array, has a value set. If it doesn't, the function assigns a default value from $defaults. To use it in the previous snippet, replace the top lines with:

function image($img) {
    $defaults = array('src'    => 'cow.png',
                      'alt'    => 'milk factory',
                      'height' => 100,
                      'width'  => 50
                     );
    $img = pc_assign_defaults($img, $defaults);
    ...
}

This is nicer because it introduces more flexibility into the code. If you want to modify how defaults are assigned, you only need to change it inside pc_assign_defaults( ) and not in hundreds of lines of code inside various functions. Also, it's clearer to have an array of name/value pairs and one line that assigns the defaults instead of intermixing the two concepts in a series of almost identical repeated lines.

6.5.4. See Also

Recipe 6.6 on creating functions that accept a variable number of arguments.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.