Created
February 13, 2009 13:35
-
-
Save davidreuss/63896 to your computer and use it in GitHub Desktop.
A bit hackish method, of getting named arguments in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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