Skip to content

Instantly share code, notes, and snippets.

@jorgepinon
Last active January 5, 2018 18:57
Show Gist options
  • Save jorgepinon/8bc3240b4f0211058b9e946c4e8f9484 to your computer and use it in GitHub Desktop.
Save jorgepinon/8bc3240b4f0211058b9e946c4e8f9484 to your computer and use it in GitHub Desktop.
php pattern : test if properties exists and set defaults
/**
* 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;
}
}
@jorgepinon
Copy link
Author

Can also store the required properties in their own variables too, and not use $obj->req_prop_1 everywhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment