Last active
January 5, 2018 18:57
-
-
Save jorgepinon/8bc3240b4f0211058b9e946c4e8f9484 to your computer and use it in GitHub Desktop.
php pattern : test if properties exists and set defaults
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
/** | |
* Function does something... | |
* @param obj $obj object with required and optional properties. | |
*/ | |
function something($obj) { | |
// bail if required properties aren't set | |
if( !isset($obj->req_prop_1) || !isset($obj->req_prop_1) ) { return ''; } | |
$opt_prop_1 = $obj->opt_prop_1; | |
$opt_prop_2 = $obj->opt_prop_2; | |
// set defaults | |
if( !isset($opt_prop_1) ) { | |
$opt_prop_1 = 'n/a'; | |
} | |
if( !isset($opt_prop_2) ) { | |
$opt_prop_2 = 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can also store the required properties in their own variables too, and not use
$obj->req_prop_1
everywhere.