It seems that this is the one example that comes up the most when wondering if it's possible to create new operations. I personally think that ?= would be quite handy.
Since creating new operators would involve creating your own PHP version, and may not very useful for others if you decide to package your code, you can instead easily create a function to emulate the same effect.
/**
* Global function to simplify the process of
* checking to see if a value equates to true
* and setting it to a new value if not.
*
* @param mixed $var the original variable to
* check and see if it equates to true/false
* @param mixed $default the default value to
* replace the variable if it equates to false
*
* @return mixed returns the variable for
* either further processing or assignment.
*/
function _d( &$var, $default ) {
return $var = $var ?: $default;
}
You can then call the function, assign it to another variable as required, or even nest them as required to assign default values down a hierarchy of variables.
_d( $variable, 'default value' );
// $variable = $variable ?: 'default value';
$variable1 = _d( $variable, 'default value' ) . 's';
// $variable1 = ( $variable = $variable ?: 'default value' ) . 's';
_d( $variable, _d( $variable1, 'default value' ) );
// $variable = $variable ?: ( $variable1 = $variable1 ?: 'default value' );
EDIT:
As a side note, the function will also assign the default value to the variable even if it has not yet been defined.
You can create a similar function, or modify the function above to the following, if you would prefer to only update the variable if it is not defined.
return $var = isset( $var ) ? $var : $default;}