Created
February 24, 2011 02:06
-
-
Save nabeelio/841613 to your computer and use it in GitHub Desktop.
array as function parameters
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 | |
// Setup our options for what we want to pass | |
$options = array( | |
'parameter1'=>'apples', | |
'parameter3'=>'grapes', | |
); | |
some_function($options); | |
function some_function($options) | |
{ | |
// Now these are the defaults | |
$defaults = array( | |
'parameter1'=>'oranges', | |
'parameter2'=>'watermelons', | |
'parameter3'=>'grapefruit', | |
'parameter4'=>'' | |
); | |
/* Now we merge the two arrays, except the $options | |
array takes precedence */ | |
$options = array_merge($defaults, $options); | |
/* extract() creates a variable with every key from the array | |
so we can use that variable directly, this is optional */ | |
extract($options); | |
// So now we can use the variables directly | |
echo $parameter1; // This will echo "apples" | |
echo $parameter2; // This will echo "watermelons" | |
/* Suppose parameter4 has to be set, so we will trigger an error | |
You can use throw as well if it's in a try/catch block */ | |
if($parameter4 == '') | |
{ | |
trigger_error('Parameter 4 must be set to this value or that value', E_USER_WARNING); | |
} | |
/* Or, if you assume that the $defaults set with '' are mandatory to fill out, | |
you can use this code */ | |
foreach($defaults as $name=>$value) | |
{ | |
if($values == '' && $options[$name] == '' || !isset($options[$name])) | |
{ | |
trigger_error("{$name} is blank, must have a value", E_USER_WARNING); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment