Been playing around a bit with both the ternary operator and null coalesce these past few weeks and really enjoy the way that it's been able to simplify a lot of my logic, especially in places where I would previously have to stack a series of if (!empty($variable))
-kinds of lines to an already annoyingly large if/else
statement. Now I can just $object->attribute = $source->attribute ?? null
, assuming I don't know if there will be an attribute in source
or not.
Now, the question that I'm having issues with is trying to figure out how to best use this for logging. Say I've got a function like:
public static function addToQueue($field, $id)
{
if ($field ?? $id ?? null == null) {
return false;
} elseif ($field != 'name' && $field != 'id') {
return false;
} elseif (Queue::where($field, $id)->count() != 0) {
return true;
} else {
Queue::insert([$field => $id]);
return true;
}
}
Fairly straightforward; you send addToQueue()
two arguments, the field
and the id
, and then it does three checks. Are any of them null
? Then return false
. Is field
something other than name
or id
? Then return false
. Is this entry already in the Queue? Then return true
(since we're interested in making sure that the entry is in the queue, not whether we added it right now or not). And, finally, if the pair is not in the queue, we add it and - again - return true
.
Now; so far so good; right? Doesn't seem to be an issue here, even though I see how I could probably make the logic inside of the function a little neater. The problem comes in my usage of it. Essentially, what I want to do is something like this - but with ternary operators:
if (QueueHandler::addToQueue($input->field, $input->value) == true) { $app->log->info($input->field . '/' . $input->value . ' added to queue.'; }
I want it to do something if the operation it carries out evaluates as true, but do nothing if it evaluates as false.
And yes, I know, it's called Ternary because you need three operations, but since PHP allows you to isset($variable) ?: echo 'Dude. It\'s not set...';
nowadays, I figured there should be a way to do the opposite, right?