Skip to content

Instantly share code, notes, and snippets.

@davidreuss
Created February 13, 2009 13:35
Show Gist options
  • Save davidreuss/63896 to your computer and use it in GitHub Desktop.
Save davidreuss/63896 to your computer and use it in GitHub Desktop.
A bit hackish method, of getting named arguments in PHP
<?php
class NamedArguments {
static function init($args) {
$assoc = reset($args);
if (is_array($assoc)) {
$diff = array_diff(array_keys($assoc), array_keys($args));
if (empty($diff)) return $assoc;
trigger_error('Bad parameters: '.join(',',$diff), E_USER_ERROR);
}
return array();
}
}
class Test {
public static function foobar($required, $optional1 = '', $optional2 = '') {
extract(NamedArguments::init(get_defined_vars()));
printf("required: %s, optional1: %s, optional2: %s\n", $required, $optional1, $optional2);
}
}
Test::foobar("required", "optional1", "optional2");
Test::foobar(array(
'required' => 'required',
'optional1' => 'optional1',
'optional2' => 'optional2'
));
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment