Created
September 4, 2014 19:13
-
-
Save miwebguy/bb3735e5f8739e523c09 to your computer and use it in GitHub Desktop.
Faking PHP Named Parameters
This file contains hidden or 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 | |
| /** | |
| * http://philsturgeon.uk/blog/2013/09/named-parameters-in-php | |
| */ | |
| public function getFriends($args) | |
| { | |
| $args += [ | |
| 'user_id' => null, | |
| 'screen_name' => null, | |
| 'cursor' => -1, | |
| 'skip_status' => false, | |
| 'include_user_entities' => false, | |
| ]; | |
| extract($args); | |
| // .... | |
| } | |
| $api->getFriends(['screen_name' => 'phpdrama', 'include_user_entities' => true]); | |
| /** | |
| * http://stackoverflow.com/questions/680368/emulating-named-function-parameters-in-php-good-or-bad-idea?rq=1 | |
| */ | |
| function pythonic(array $kwargs) | |
| { | |
| extract($kwargs); | |
| // .. rest of the function body | |
| } | |
| // if params are optional or default values are required | |
| function pythonic(array $kwargs = array('name'=>'Jon skeet')) | |
| { | |
| extract($kwargs); | |
| // .. rest of the function body | |
| } | |
| /** | |
| * http://stackoverflow.com/questions/680368/emulating-named-function-parameters-in-php-good-or-bad-idea?rq=1 | |
| */ | |
| function myFunc (array $args) { | |
| $default = array( | |
| "name" => "John Doe", | |
| "age" => "30" | |
| ); | |
| // overwrite all the defaults with the arguments | |
| $args = array_merge($defaults, $args); | |
| // you *could* extract($args) here if you want | |
| echo "Name: " . $args['name'] . ", Age: " . $args['age']; | |
| } | |
| myFunc(array("age" => 25)); // "Name: John Doe, Age: 25" | |
| /** | |
| * http://stackoverflow.com/questions/1620737/using-default-value-when-calling-a-function | |
| */ | |
| function test($options = array()) { | |
| $defaults = array( | |
| 't1' => 'test1', | |
| 't2' => 'test2', | |
| 't3' => 'test3', | |
| ); | |
| $options = array_merge($defauts, $options); | |
| extract($options); | |
| echo "$t1, $t2, $t3"; | |
| } | |
| Call your function this way : | |
| test(array('t3' => 'hi, i am different')); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment