Skip to content

Instantly share code, notes, and snippets.

@lsemel
Created November 21, 2010 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lsemel/709147 to your computer and use it in GitHub Desktop.
Save lsemel/709147 to your computer and use it in GitHub Desktop.
Flexible named and positional parameters for PHP
<?php
/**
* Flexible named and positional parameters for PHP
*
* To use in your function, call it like this:
*
* function your_function() {
* $opts = defaults(func_get_args(),array(
* 'some_param'=> 'default',
* 'another_param'=> 'default',
* 'yet_another_param => 'default'
* ), array('yet_another_param','another_param'));
* # ...
* }
*
* If you call your_function with an array as the first parameter, it will assume named parameters
* Calling with anything else as the first parameter, positional parameters will be assumed
*
* $defaults is a hash mapping parameter names to default values
* $positional is a list of key names map positional parameters to, if the calling function is called without an array as the first parameter
*/
function defaults($passed,$defaults = array(),$positional = array()) {
if (count($passed) > 0 && !is_array($passed[0]) && $positional) {
$orig = $passed;
$passed = array();
foreach ($orig as $v) {
$k = array_shift($positional);
$passed[0][$k] = $v;
}
}
if (is_array($passed[0])) {
$result = $passed[0];
} else {
$result = array();
}
foreach ($defaults as $k => $v) {
$result[$k] = array_key_exists($k,$result) ? $result[$k] : $v;
}
return $result;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment