ifnotset function in php

Here is a simple php function that acts like a ternary if-else operator, but is a bit shorter. I believe groovy has something similar, that is; native support for what I’m trying to do…

The crux:

// old school
if(var1 == null) {
  var1 = var3;
} else { // this else is really unnecessary
  var1 = var1;
}
// modified above example
if(var1 == null) var1 = var3;

or

if(!var1) var1 = var3;

// ternary
var1 = var1 == null ? var3 : var1;

// ternary shorthand
var1 = var1 ?: var3;

The problem with all of the above examples is that php complains if a variable isn’t set or defined. At least php 5.3 does on standard settings. And you are still repeating var1.

The real way this should be done, and I believe this is how groovy does it is the following…

var1 ?= var3;

But, my function syntax is…

setifnot(var1, var3);

This function uses isset (so no php complaining about undefined variables) and uses a pass by reference to the function, so we only need to write out the variable once. I don’t know, I prefer to stay within the confines of the native syntax, but I also don’t like repeating myself / nor turning off error messages / nor declaring variables at the top of the file and nulling them out. I suppose my CS prof would be thrilled, but I’m lazy.

See source below:

<?php

// ternary type expression
function setifnot(&$value, $defaultValue) {
$value = isset($value) ? $value : $defaultValue;
}

$setvar = “5”;
setifnot($setvar, “7”);
echo “Nothing changed with setvar [” . $setvar . “] because it was already set.”;

echo “<br />\n\r”;

setifnot($unsetvar, “8”);
echo “Unsetvar is now set to [” . $unsetvar . “]”;

?>

Published by and tagged Code using 295 words.