6.5. Using Named Parameters6.5.1. ProblemYou want to specify your arguments to a function by name, instead of simply their position in the function invocation. 6.5.2. SolutionHave the function use one parameter but make it an associative array:
6.5.3. DiscussionWhile 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:
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:
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:
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 AlsoRecipe 6.6 on creating functions that accept a variable number of arguments.
Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|