6.4. Using Named Parameters
Problem
You want to specify your arguments to a function by name, instead of simply their position in the function invocation.
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'));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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access