PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 6.5 Using Named Parameters

6.5.1 Problem

You want to specify your arguments to a function by name, instead of simply their position in the function invocation.

6.5.2 Solution

Have the function use one parameter but make it an associative array:

function image($img) {
    $tag  = '<img src="' . $img['src'] . '" ';
    $tag .= 'alt="' . ($img['alt'] ? $img['alt'] : '') .'">';
    return $tag;
}

$image = image(array('src' => 'cow.png', 'alt' => 'cows say moo'));
$image = image(array('src' => 'pig.jpeg'));

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.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    Chapter 5. Variables
    Chapter 6. Functions
    6.1 Introduction
    Recipe 6.2 Accessing Function Parameters
    Recipe 6.3 Setting Default Values for Function Parameters
    Recipe 6.4 Passing Values by Reference
    Recipe 6.5 Using Named Parameters
    Recipe 6.6 Creating Functions That Take a Variable Number of Arguments
    Recipe 6.7 Returning Values by Reference
    Recipe 6.8 Returning More Than One Value
    Recipe 6.9 Skipping Selected Return Values
    Recipe 6.10 Returning Failure
    Recipe 6.11 Calling Variable Functions
    Recipe 6.12 Accessing a Global Variable Inside a Function
    Recipe 6.13 Creating Dynamic Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele